Sunday, December 1, 2013

Javascript - Why Assign this value in self

In Javascript, we see this line of code frequently
self = this;

We know this refers to the invocation context, but why we need to assign its value to a variable. The reason is this keyword does not have a scope, and nested functions do not inherit the this value of their caller. Thus if a nested function is invoked as a function, its this keyword actually refers to global object (non-strict mode) or undefined (strict mode). In order to access the invocation context of the outer function, we need to assign the value of this keyword to a variable. Recalling from our previous blog Variable Scope & Function Scope, we have variables are visible within the function in which they are defined and within any functions that are nested within that function. Now let's take a look at the following code snippet.

var o = {
  m: function(){
    var self = this;

    console.log(this===o);   // return true
    f(); //invoking nested function as a function

    //nested function
    function f(){
      console.log(this===o);  // return false
      console.log(self===o);  // return true
    }
  }
}

o.m();

No comments:

Post a Comment