The this Keyword Runtime Semantics

A function’s this keyword in JavaScript have a different behavior than other languages, even it will represent different behavior between strict mode and non-strict mode. In JavaScript while executing a function this keyword plays a vital role.
Global Ref:
If there is no parent/owner for a function, it will execute as global function.

var noParentFunction = function () {
console.log(toString.call(this)); // [object Window]
};
//Call Method
noParentFunction();

When we execute noParentFunction function it will yield this object reference as window(global ref). As per JavaScript lexical rules if there is no specific parent of a function it will fall under window. There is no deference between below two statements:

noParentFunction();
Window.noParentFunction();

Object Ref:
Whenever we call parent.child() child function always get this scope as parent’s. now we create a parent, it will have function child:

var parentClass = {
name:'parent',
childMethod: function (){console.log(this === parentClass);} //->true
};
// call the method
parentClass.childMethod();//->true

Inherited Function:
when we create parent function, use this keyword inside to transfer your properties when object inherited.

var parentClass = function(){
//attach childMethod to parentClass scope by using this keyword
this.childMethod= function (){console.log(this);};
};
// Inherited parent1
var parent1 = new parentClass();
// call the method
parent1.childMethod();//->parentClass

Inherited function with prototype:
Same as above inherited prototype methods this scope works.

var parentClass = function(){
//attache childMethod to parentClass scope by using this keyword
this.childMethod= function (){console.log(this);};
};
//add prototype methode
parentClass.prototype.parentPrototype = function ()
{
console.log(this);
}
// call the method
var parent1 = new parentClass();
parent1.childMethod();//->parentClass
parent1.parentPrototype();//->parentClass

Leave a Reply

Your email address will not be published. Required fields are marked *