使用 setInterval 调用的 Javascript 绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11241607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:31:07  来源:igfitidea点击:

Javascript binding using call with setInterval

javascriptbindingcallsetintervalobject-literal

提问by d13

How can I use "call" with "setInterval" to get an object literal to invoke one of its own methods?

如何使用“调用”和“setInterval”来获取对象文字来调用它自己的方法之一?

Here's an example. This works, and I understand why it works. The timer object calls its own tick method once each second

这是一个例子。这有效,我理解它为什么有效。定时器对象每秒调用一次自己的tick方法

var timer =
{ 
  start: function()
  {
    var self = this;
    setInterval(function(){self.tick();}, 1000);

  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I tried to simplify this code by using "call". This next example is the best that I came up with. But it doesn't work: the tick method is called only once, and then I get a type error.

我试图通过使用“调用”来简化这段代码。下一个例子是我想出的最好的例子。但它不起作用:tick 方法只被调用一次,然后我得到一个类型错误。

var timer =
{ 
  start: function()
  {
    setTimeout.call(this, this.tick(), 1000);
  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I think I don't really understand how call works. Can anyone explain what I'm doing wrong?

我想我真的不明白通话是如何工作的。谁能解释我做错了什么?

回答by Esailija

You are .calling.setIntervalnot your callback function which the browser calls:

.calling.setInterval不是浏览器调用的回调函数:

setInterval( this.tick.bind(this), 1000 );

Should work. See .bind

应该管用。看.bind

回答by d13

This is what I ended up with:

这就是我最终的结果:

  var timer = {
    time: 0,
    start: function() {
      var timerTick = this.tick.bind(this);
      window.setInterval(function() {
        timerTick();
      }, 1000);
    },
    tick: function() {
      this.time += 1;
      console.log(this.time);
    }
  };

  timer.start();