Copied from: https://stackoverflow.com/a/16063711/1641941
The this variable
In all the example code you'll see this
referring to the current instance.
The this variable actually refers to the invoking object, it refers to the object that came before the function.
To clarify see the following code:
theInvokingObject.thefunction();
The instances where this would refer to the wrong object are usually when attaching event listeners, callbacks or timeouts and intervals. In the next 2 lines of code we pass
the function, we don't invoke it. Passing the function is: someObject.aFunction
and invoking it is: someObject.aFunction()
. The this
value does not refer to the object the function was declared on but on the object that invokes
it.
setTimeout(someObject.aFuncton,100);//this in aFunction is window
somebutton.onclick = someObject.aFunction;//this in aFunction is somebutton
To make this
in the above cases refer to someObject you can pass a closure instead of the function directly:
setTimeout(function(){someObject.aFuncton();},100);
somebutton.onclick = function(){someObject.aFunction();};
I like to define functions that return a function for closures on the prototype to have fine control over the variables that are included in the closure scope.
var Hamster = function(name){
var largeVariable = new Array(100000).join("Hello World");
// if I do
// setInterval(function(){this.checkSleep();},100);
// then largeVariable will be in the closure scope as well
this.name=name
setInterval(this.closures.checkSleep(this),1000);
};
Hamster.prototype.closures={
checkSleep:function(hamsterInstance){
return function(){
console.log(typeof largeVariable);//undefined
console.log(hamsterInstance);//instance of Hamster named Betty
hamsterInstance.checkSleep();
};
}
};
Hamster.prototype.checkSleep=function(){
//do stuff assuming this is the Hamster instance
};
var betty = new Hamster("Betty");