this keyword

this keyword:

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.

Example:

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.

Example
//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’.

Example
//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 .