JavaScript *this* keyword
Sons of JavaScript Collection | this article
While using JavaScript one wonders what the this keyword means on different scenarios.
You may start using it on a click event of a DOM element, maybe using the constructor pattern and the list goes on. Then you start seeing it being used in more advanced scenarios where this is changed behind the scenes.
These are the uses of this you should be familiar with:
Pointing to the global scope (window)
var number = 7;
console.log(this.number === window.number); // true
...
another = 8; // global variable
console.log(this.another === window.another); // true
...
//within a function this is set to window
function Fn() {
return this;
};
console.log(Fn() === window); // true
Pointing to an object literal
// object scope
var scope = {
number: 7,
Fn: function() {
return this.number;
}
};
// this points to scope (not window)
console.log(scope.Fn()); // 7
Pointing to a new object using new keyword
//constructor function
function Person(id) {
//new keyword implicit this = {};
this.id = id;
//new keyword implicit return this;
};
//this points to new object
var person = new Person(1);
Pointing to an object using call or apply
function Fn(a, b) { return a + b + this; };
// implicit this = 1
console.log(Fn.call(1, 2, 3)); //6
console.log(Fn.apply(1, [2, 3])); //6
//note: if null is passed this = window
Used on a DOM event handler
<!-- this is set to the DOM element -->
<a href="#" class="myclass another" id="1" onclick="alert(this.id + ' ' + this.className)">DOM element</a>
Reference: Mozilla JavaScript Reference link
Written by gerardsans
Related protips
4 Responses
Dont forget .bind( this ) with .call and .apply. Its quite handy if for instance you do not wanna lose scope when attaching an event listener in a class like function.
If you take the concepts you demonstrate in this article with scope, and remember them in a few of your other articles, you'll be able to address the issues I pointed out. You use this
appropriately here, but in some other articles you have the behavior of this
described incorrectly.
Start here (use kfwerf's suggestion also, and expand this basic understanding out to edit your other tips, and you'll be on track.
@kfwerf Bind is not necessary. That is exactly what the first parameter does on call and apply. Just replace on my example Fn.call(this,2,3) or Fn.apply(this,[2,3]).
@longlivechief maybe you could write your own pro tip on the topic?