How “this” keyword works in JavaScript?

What is “this” keyword in JavaScript

this is a special object in JavaScript. It is entirely dependent in which context a code is executed. this is a property of active execution context object.

activeExecutionContext = {
  VO: {VO1, VO2, ...}, // VO = variable object
  this: {} // speical object
};

The value of the keyword this varies baesd on the execution context. this keyword value is set when the program enters in the context.

“this” is immutable

The value of the keyword this is immutable while the code is running in the context as this is not a variable.

var myschoolObj = {name: "Jefferson Smith"};
var myObj = {
    name: "Jef",
    getName: function () {
        this = myschoolObj; // Uncaught ReferenceError: Invalid left-hand side in assignment
        console.log(this.name);
    }
};
myObj.getName();

Basic of determining the value of “this”

Lets consider the following example:

var name = "Joe Smith";
var myObj = {
    name: "Jennifer Smith",
    getName: function () {
        console.log(this.name);
    }
}
myObj.getName();             // Jennifer Smith
(newObj = myObj.getName)();  // Joe Smith

To understand why the same method prints two different names we need to get into the basic of the keyword this. In EcmaScript we have mechanism called References that are not visible to public. References are important to scripting language engine implementors.

References is an abstract entity that consists of three components — base, name, and strict flag. We will not consider strict flag for now. So the References can be presented using following pseudo-code:

var Reference = {
  base: ,
  propertyName: 
};

References are created for following two cases:

  • In the process of Identifier resolution // i.e. myObj creates a reference
  • During property access // i.e. myObj.getName creates a reference

How the Reference is related with the keyword “this”?

When a Reference is created the keyword this is set to base attribute value of Reference object.

Explanation of myObj.getName() with Reference

myObj.getName() creates a reference and following is the Reference object:

var getNameReference = {
  base: myObj,
  propertyName: 'getName'
};
// this == getNameReference.base == myObj

This is why the keyword this is set to myObj inside getName method.

Explanation of (newObj = myObj.getName)() with Reference

In this case myObj.getName gets assigned to newObj that transforms myObj.getName Reference into an actual function object.

Here is a good video about “this” in JavaScript:

Share