I am happy it works but still a bit confused of what the scope of the "me" variable is in the following code. Using it for a while now but can't figure out why it works.
var timer=function(){
this.timerMember=1;
this.timerID=0;
this.startTimer=function(){
var me=this;
this.timerID=setTimeout(function(){
//shares scope with this.startTimer
//timerMember is 2 here
console.log(me.timerMember);
// this is window
console.log(this);
// me doesn't exist in window
console.log(this.me);
},0);
// this code gets executed before anonymous
// timer function
// clearTimeout(this.timerID);
this.timerMember++;
}
}
var t=new timer();
t.startTimer();
The anonymous function passed to setTimeout seems to share scope with timer.startTimer yet startTimer is obviously finished when the anonymous function executes (me.timerMemer=2) so when startTimer is done the me variable should be out of scope. Lucky for me JavaScript keeps it until the anonymous function is executed (works on all browsers) but I wonder if this is the right way. Is this behavior by design or just a fortunate accident?
1 Answer 1
It's by design. It's called a closure.
When a function is defined inside another function, the local variables in the outer function is put in a closure, so that they survive even after the outer function ends. The inner function holds on to the closure so that it can accesses the variables later on.
var me = this;
you can just dothis.timerID=setTimeout(function(){}.bind(this), 2)
in some cases.bind
is a relatively recent feature, not supported until IE 9, Firefox 4.0, etc.