Javascript this keyword refers current object in a method or constructor. It eliminates the confusion between the same object attributes & parameters name.
To access javascript object property from the method of the same object, use this
keyword. Let us understand it with the help of an example.
Source Code
const person = {
name: "John Doe",
age: 30,
// accessing name property by using this.name
basicInfo: function () {
console.log("My name is " + " " + this.name);
},
};
person.basicInfo();
Code Explanation
In the above example, this
keyword is used to access object property.
Please keep in mind that this
keyword refers to the current object.
If a function inside an object has a variable then it can be accessed in the normal way. Let us understand it with the help of an example.
Source Code
const person = {
name: "John",
age: 30,
getUserInfo: function () {
let surname = "Doe";
document.write("Hello,my name is " + " " + this.name + " " + surname);
},
};
person.getUserInfo();