Keyword “this” is immutable in JavaScript
“this” is immutable
this
is a special object in JavaScript. It is entirely dependent on which context a code is executed. The value of the keyword this
varies based on the execution context. this
keyword value is set when the program enters the context. It is impossible 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. Let’s 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 a call or apply
var myschoolObj = {name: "Jefferson Smith"}; var myObj = { name: "Jef", getName: function () { console.log(this.name); } }; myObj.getName.call(myschoolObj);