JavaScriptthis Keyword
this in Objects
Thethis keyword refers to an object.
In JavaScript,this is used to accessthe object that is calling a method.
this in an Object Method
When used inside an object method,this refers to the object.
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Try it Yourself »firstName: "John",
lastName: "Doe",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In the example above:
this.firstNamerefers to thefirstNameproperty of the person objectthis.lastNamerefers to thelastNameproperty of the person object
Why Use this?
Thethis keyword makes it possible to use the same method with different objects.
Example
const person1 = {
name: "John",
hello: function() {
return "Hello " + this.name;
}
};
const person2 = {
name: "Anna",
hello: function() {
return "Hello " + this.name;
}
};
document.getElementById("demo").innerHTML = person1.hello();
Try it Yourself »name: "John",
hello: function() {
return "Hello " + this.name;
}
};
const person2 = {
name: "Anna",
hello: function() {
return "Hello " + this.name;
}
};
document.getElementById("demo").innerHTML = person1.hello();
this Alone
When used alone,this refers to the global object.
In a browser, the global object is thewindow object.
Note: In strict mode,this isundefined when used alone.
this in a Function
In a regular function,this also refers to the global object.
Example
function myFunction() {
return this;
}
document.getElementById("demo").innerHTML = myFunction();
Try it Yourself �return this;
}
document.getElementById("demo").innerHTML = myFunction();
Summary
- In an object method,
thisrefers to the object thislets methods access object properties- Used alone,
thisrefers to the global object

