我无法在我的闭包内找到正确的范围

时间:2014-10-23 10:07:41

标签: javascript function closures

我的闭包中有一个setInterval但是我无法正确定位闭包内的变量。如何正确定位变量并在计数器达到finishTime时停止间隔?

 var counter = function() {
    return {
       myInterval: null,
       counter: 0,
       finishTime: 1000,
       startTimer: function() {
          this.myInterval = setInterval(this.repeat,10);
       },
       repeat: function() {
          if(this.counter==this.finishTime) clearInterval(this.myInterval);
          this.counter++;
       }
    }
 };

counter().startTimer();

2 个答案:

答案 0 :(得分:1)

在本地范围内定义所有内容(如果您还想从外部访问它,可以选择为返回的对象分配重复):

var Counter = function(finish)
{
 var count = 0;
 var myInterval = null;

 function repeat() {
  if(++count == finish)
   clearInterval(myInterval);
 }

 return {
      getCount: function() { return count; },
      startTimer: function() { myInterval = setInterval(repeat,10); return this; },
      repeat: repeat
 };
};

var counter = new Counter(1000).startTimer();

答案 1 :(得分:1)

 var counter = function() {
    return {
       myInterval: null,
       counter: 0,
       finishTime: 1000,
       startTimer: function() {
          this.myInterval = setInterval(this.repeat.bind(this), 10);//need to bind the context here
       },
       repeat: function() {
           if(this.counter==this.finishTime)
           { 
               clearInterval(this.myInterval);
               console.log("finished")
            }
          this.counter++;
       }
    }
 };

counter().startTimer();