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());