In JavaScript, the this keyword operates a little differently than in other languages. There are also some distinctions between stringent and non-strict modes.
The this keyword refers to different objects depending 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.
this in a Method:
When used in an object method, this refers to the object.
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 used alone, this refers to the global object.
Because this is running in the global scope.
In a browser window the global object is [object Window]
let x = this;
console.log(x) //output is :[object Window]
In strict mode, when used alone, this also refers to the global object:
"use strict:";
let x = this;
console.log(x) //output is :[object Window]
this in a Function(Default):
In a function, the global object is the default binding for this.
In a browser window the global object is [object Window]:
function myFunction() {
return this;
}
myFunction() //output is : [object Window]
this in a Function (Strict):
JavaScript strict mode does not allow default binding.
So, when used in a function, in strict mode, this is undefined.
"use strict";
function myFunction() {
return this;
}
myFunction() //output is : undefined
this in Event Handlers:
In HTML event handlers, this refers to the HTML element that received the event:
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
Top comments (0)