- this is a JS keyword that is vastly misunderstood by even experienced developers.
- this is a special identifier keyword that's automatically defined in the scope of every function but what it actually refers to is what we need to understand.
- Before proceeding with understanding what this is, we will first see what this isn't.
- Itself
- Its Scope
- Itself Many developers believe that this refers to the function itself in which it is called which is wrong. Below is a simple example to prove it.
function foo(num) {
console.log("foo: " + num);
// keep track of how many times `foo` is called
this.count++;
}
// Create a property to the function object
foo.count = 0;
var i;
for(i=0; i<10; i++) {
if(i > 5) {
foo(i);
}
}
console.log(foo.count); // 0 which means *this* doesn't refers the function itself
- In case you are curious, here is the correct way to refer to the function scope itself using this which we will further understand in the next chapters:
function foo(num) {
console.log("foo: " + num);
// keep track of how many times `foo` is called
this.count++;
}
// Create a property to the function object
foo.count = 0;
var i;
for(i=0; i<10; i++) {
if(i > 5) {
// Using *`call(..)`*, we ensure the `*this`* points at the
// function object *(`foo`)* itself
foo.call(foo, i);
}
}
console.log(foo.count); // 4
- Its Scope Another famous misconception developers have is that they think that it refers to the function's scope. It is a tricky one because it is somewhat true but it is quite misguided in another sense. To be clear, this doesn't refer to the lexical scope of the function in any way. Here developer is trying to create a bridge between the lexical scopes of foo() and bar(), so that bar() has access to the variable
a
in the inner scope of foo(). No such bridge is possible. Let's use an example again to prove this:
function foo() {
var a = 2;
// This magically works and doesn't gives error
// but we will explain this in future chapter
this.bar();
}
function bar() {
console.log(this.a);
}
foo(); // ReferenceError: a is not defined
- Having set aside all myths, let's see how this really works. It is not an author-time binding but is a runtime binding that is based on the conditions of the function's invocation which means it has nothing to do with where the function is declared but has instead everything to do with the manner in which function is called.
- When a function is invoked, an execution context is created which is nothing but an activation record containing info about where the function was called from, how it was called, what parameters were passed, etc. One of the properties passed is the this reference which is used for the duration of the function's execution.