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

var name = "Narendra";
function displayName() {
console.log(this.name);
}
displayName(); // "Narendra"
view raw gistfile1.js hosted with ❤ by GitHub

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

function displayName() {
console.log(this.name);
}
displayName(); // "undefiend"
view raw gistfile1.js hosted with ❤ by GitHub

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

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"
view raw gistfile1.js hosted with ❤ by GitHub

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

function displayName() {
console.log(obj1.name);
}
view raw gistfile1.js hosted with ❤ by GitHub

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

function displayName() {
console.log(obj2.name);
}
view raw gistfile1.js hosted with ❤ by GitHub

link - implicit binding

Rule 5 - New Keyword  

No comments:

Post a Comment