In JavaScript, the this
keyword is used to refer to an object. The object that this
refers to depends on how it is used.
- In an object method,
this
refers to the object. - Alone,
this
refers to the global object. - In a function,
this
refers to the global object. - In a function, in strict mode,
this
is undefined. - In an event,
this
refers to the element that received the event. - Methods like
call()
,apply()
, andbind()
allowthis
to refer to any object.
Note: this
is not a variable. It is a keyword. Its value cannot be changed manually.
this
in an Object Method
When used inside an object method, this
refers to the object itself.
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Output: John Doe
this
Alone
When this
is used alone, it refers to the global object in a browser (which is window
).
let x = this;
console.log(x); // Output: [object Window] (in a browser)
In strict mode, this
alone is undefined
.
"use strict";
let x = this;
console.log(x); // Output: undefined
this
in a Function (Default)
By default, inside a function, this
refers to the global object.
function myFunction() {
return this;
}
console.log(myFunction());
// Output: [object Window] (in a browser)
this
in a Function (Strict Mode)
In strict mode, a function’s this
is undefined
.
"use strict";
function myFunction() {
return this;
}
console.log(myFunction()); // Output: undefined
this
in Event Handlers
In an event handler, this
refers to the HTML element that received the event.
<button onclick="this.style.display='none'">Click to Remove Me!</button>
Object Method Binding
Inside an object method, this
refers to the object itself.
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
myFunction: function() {
return this;
}
};
console.log(person.myFunction()); // Output: [object Object]
Explicit Function Binding
The call()
and apply()
methods allow us to set this
explicitly.
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const person2 = {
firstName: "John",
lastName: "Doe",
};
console.log(person1.fullName.call(person2)); // Output: John Doe
Function Borrowing with bind()
With bind()
, an object can borrow a method from another object.
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
const member = {
firstName: "Hege",
lastName: "Nilsen",
};
let fullName = person.fullName.bind(member);
console.log(fullName()); // Output: Hege Nilsen