In the global execution context, this keyword refers to the global object which is window.
Generally, this keyword will refer to the object it belongs to.
console.log(this) //Prints: Window
var myVar = 'Donald';
function WhoIsThis() {
var myVar = 'Trump';
console.log(myVar); //Print: Trump
console.log(this.myVar); //Print: Donald
}
WhoIsThis(); // inferred as window.WhoIsThis()
In a method, this refers to the owner object.
//this keyword in an object
var person = {
name: "Ameer",
getName: function () {
console.log(this.name);
},
};
console.log(person.getName()); //Print: Ameer
In above example, at the time of invocation, the getName function is a property of the object person, therefore the this keyword will refer to the object object person , hence the output is ‘Ameer’.
//this keyword in an object
var person = {
name: "Ameer",
getName: function () {
console.log(this.name);
},
};
var getName = person.getName;
var newPerson = {name: "Rakesh", getName}
console.log(newPerson.getName()) //Prints: Rakesh
In above example, although the getName function is declared inside the object person , at the time of invocation, getName() is a property of newPerson , therefore the “this” keyword will refer to object newPerson .