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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var name = "Narendra"; | |
function displayName() { | |
console.log(this.name); | |
} | |
displayName(); // "Narendra" |
Here call side is nothing, then value of "this" is global object(Window) and display "Narendra" because name is defined in global scope.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName() { | |
console.log(this.name); | |
} | |
displayName(); // "undefiend" | |
Here call side is nothing then value of "this" is global object(Window) and display "undefined" because name is not defined in global scope.
link1 - default binding
link2 - default bindingRule 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName() { | |
console.log(this.name); | |
} | |
var obj1 = {name: "Deepak", displayName: displayName}; | |
var obj2 = {name: "Chetan", displayName: displayName}; | |
obj1.displayName(); | |
// Here value of "this" is obj1 and it display "Deepak" | |
obj2.displayName(); | |
// Here value of "this" is obj2 and it display "Chetan" |
In the above example when we write obj1.displayName() then displayName function become.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName() { | |
console.log(obj1.name); | |
} |
and when we write obj2.displayName() then displayName function become.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function displayName() { | |
console.log(obj2.name); | |
} |
link - implicit binding
Rule 5 - New Keyword
No comments:
Post a Comment