我可以'我没有针对我的闭包中的正确范围

I can't target the correct scope inside my closure

本文关键字:闭包 我的 范围 我可以      更新时间:2023-09-26

我的闭包中有一个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();
 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();

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

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