const person = { firstName: “John”, lastName : “Doe”, id : 5566, fullName : function() { return this.firstName + ” “ + this.lastName; } }; |
In JavaScript, the this
keyword refers to an object, and the specific object it points to depends on how it is used.
In an object method, this refers to the object that owns the method. |
When used alone, this refers to the global context. |
In a function, this refers to the global object. |
In a function, when in strict mode, this is undefined. |
In an event handler, this refers to the element that triggered the event. |
Methods like call(), apply(), and bind() can explicitly set this to refer to any object. |
Note: this is not a variable; it is a keyword. You cannot modify its value. |
When used in an object method, this refers to the object itself.
In the example above, this refers to the person object because the fullName method is a method of the person object.
fullName : function() { return this.firstName + ” “ + this.lastName; } |
When used alone, this refers to the global object, as it is executing in the global scope.
In a browser environment, the global object is [object Window].
let x = this; |
In strict mode, when used alone, this still refers to the global object.
“use strict”; let x = this; |
In a function, the global object is the default binding for this.
In a browser environment, the global object is [object Window].
function myFunction() { return this; } |
JavaScript strict mode does not allow default binding for this. Therefore, when used in a function in strict mode, this is undefined.
“use strict”; function myFunction() { return this; } |
In HTML event handlers, this refers to the HTML element that triggered the event.
<button onclick=”this.style.display=’none'”> Click to Remove Me! </button> |
In these examples, this refers to the person object.
const person = { firstName : “John”, lastName : “Doe”, id : 5566, myFunction : function() { return this; } }; |
const person = { firstName: “John”, lastName : “Doe”, id : 5566, fullName : function() { return this.firstName + ” “ + this.lastName; } }; |
In other words, this.firstName refers to the firstName property of this (the person object).
The call() and apply() methods are built-in JavaScript methods that allow you to invoke an object method with a different object as the argument.
The example below calls person1.fullName with person2 as the argument. In this case, this refers to person2, even though fullName is a method of person1.
const person1 = { fullName: function() { return this.firstName + ” “ + this.lastName; } } const person2 = { firstName:“John”, lastName: “Doe”, } // Return “John Doe”: person1.fullName.call(person2); |