Keyword “this” is immutable in JavaScript

“this” is immutable

this is a special object in JavaScript. It is entirely dependent in which context a code is executed. The value of the keyword this varies baesd on the execution context. this keyword value is set when the program enters in the context. It is NOT possible to reassign this with another object.

As this is not a variable but a special object in JavaScript, any attempt to assign an object to this will throw a ReferenceError. Lets consider the following example:

var myschoolObj = {name: "Jefferson Smith"};
var myObj = {
    name: "Jef",
    getName: function () {
        console.log(this.name);
    }
};
myObj.getName();

Attempt to reassign “this” at runtime

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

Change “this” binding with call or apply

var myschoolObj = {name: "Jefferson Smith"};
var myObj = {
    name: "Jef",
    getName: function () {
        console.log(this.name);
    }
};
myObj.getName.call(myschoolObj);
Share