1

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?

asked Jan 13, 2013 at 3:42
8
  • 5
    This is standard JavaScript "closure" behaviour. (Certainly not an accident.) Commented Jan 13, 2013 at 3:43
  • Instead of doing var var me = this; you can just do this.timerID=setTimeout(function(){}.bind(this), 2) in some cases. Commented Jan 13, 2013 at 3:46
  • @PeeHaa: bind is a relatively recent feature, not supported until IE 9, Firefox 4.0, etc. Commented Jan 13, 2013 at 3:48
  • 1
    IE9 ok, but are you really worried firefox 3? :P Note that FF is currently on v1228 ;) Commented Jan 13, 2013 at 3:49
  • @PeeHaa: What does "v1228" mean? Firefox is currently at version 18.0. Commented Jan 13, 2013 at 4:01

1 Answer 1

5

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.

answered Jan 13, 2013 at 3:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.