Friday, December 19, 2014

This Keyword in JavaScript

Every function while executing has a reference to its current execution context called this.
                                                          or
In JavaScript whenever a function execute it contain this keyword in its execution context.

There are 5 rule to identify the value of this

Rule 1 - Default binding
a.b.c() here a.b is called "call side" and c() is function, inside function c the value of "this" is a.b


Here call side is nothing, then value of "this" is global object(Window) and display "Narendra" because name is defined in global scope.


Here call side is nothing then value of "this" is global object(Window) and display "undefined" because name is not defined in global scope.

link2 - default binding

Rule 2 - Implicit binding 
a.b.c() here a.b is called "call side" and c() is function, inside function c the value of "this" is a.b


In the above example when  we write obj1.displayName() then displayName function become.


and when we write obj2.displayName() then displayName function become.


link - implicit binding

Rule 5 - New Keyword  

No comments:

Post a Comment