Skip to Main Content

Incorrect Scope in JavaScript Function Invocation

When using the function invocation pattern (e.g. myFunc()) in JavaScript, the this variable is incorrectly bound to the global object. Ex.

var val = 2;
var obj = {
  val : 0,
  method : function(){
    function times(x){
      return this.val * x;
    }
    return times(5); // 10
  }
}
console.log(obj.method());

In the above example we would expect this.val to reference obj.val and therefore return 0. But instead this.val references window.val, and thus returns 10.

A work around for this incorrect scope in JavaScript is to create a new variable to store the higher order function's context. Below we use a variable named that to hold the scope of the outer function and then use that.val, which will reference obj.val.

var val = 2;
var obj = {
  val : 0,
  method : function(){
    var that = this; // 
    function times(x){
      return that.val * x;
    }
    return times(5); // 0
  }
}
console.log(obj.method());

Clear DNS Cache on Mac OS X

$ sudo dscacheutil -flushcache
$ sudo killall -HUP mDNSResponder

Most RecentRSS

ArchiveRSS

March 2016 (1)
January 2016 (1)
September 2015 (1)
May 2015 (1)
April 2015 (1)
March 2015 (1)
February 2015 (2)
January 2015 (5)
September 2014 (2)
August 2014 (4)
July 2014 (1)
March 2014 (1)
November 2013 (3)
September 2013 (3)
July 2013 (6)
June 2013 (1)
May 2013 (1)
March 2013 (2)
February 2013 (3)
January 2013 (4)