JavaScript this Keyword
This in object-oriented languages represents a reference to the current object.
But in JavaScript this is not fixed, it will change as the execution environment changes.
In the method, this represents the object to which the method belongs.
If used alone, this represents the global object.
In the function, this represents the global object.
In functions, in strict mode, this is undefined.
In the event, this represents the element receiving the event.
Similar to call() and apply() methods can refer this to any object.
Example
var person = { firstName: "John", lastName: "Doe", id: 5566, fullName: function() { return this.firstName + "" + this.lastName; } };
This in the method
In an object method, this points to the object on which it is called.
In the above example, this represents the person object.
The object to which the fullName method belongs the person.
Example
fullName: function() { return this.firstName + "" + this.lastName; }
Use this alone
Use this alone, it points to the global object.
In the browser, window is the global object as [ object Window ]:
Example
var x = this;
In strict mode, if used alone, this also points to the Global object.
Example
"use strict"; var x = this;
Use this in the function (default)
In a function, the owner of the function is bound to this by default.
In the browser, window is the global object as [ object Window ]:
Example
function myFunction() {
return this;
}
Use this in the function (strict mode)
In strict mode, the function is not bound to this, and this is undefined at this time .
Example
"use strict"; function myFunction() { return this; }
This in the event
In the HTML event handler, this points to the HTML element receiving the event:
Example
<button onclick="this.style.display='none'"> Click me and I will be disappeared </button>
Object method binding
In the following example, this is the person object, and the person object is the owner of the function:
Example
var person = { firstName: "John", lastName: "Doe", id: 5566, myFunction: function() { return this; } };
Example
var person = { firstName: "John", lastName: "Doe", id: 5566, fullName: function() { return this.firstName + "" + this.lastName; } };
Explanation: this.firstName represents the firstName property of this (person) object .
Explicit function binding
In JavaScript, functions are also objects, and objects have methods. Apply and call are methods of function objects. These two methods are extremely powerful, they allow to switch the context of function execution, that is, the object bound by this.
In the following example, when we call the person1.fullName method with person2 as a parameter, this will point to person2, even if it is a method of person1:
Example
var person1 = { fullName: function() { return this.firstName + " " + this.lastName; } } var person2 = { firstName:"Jake", lastName: "C", } person1.fullName.call(person2); // returns "John Doe"