使用 window.setInterval 在现有对象上执行方法 [英] execute a method on an existing object with window.setInterval

查看:46
本文介绍了使用 window.setInterval 在现有对象上执行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 window.setInterval 方法超时时在现有对象上运行该方法.我可以通过使用一些全局变量并在 setInterval 中调用此全局变量的方法来模拟相同的情况,但我想知道是否可以直接使用该方法.

Is it possible to run the method on an existing object on timeout of window.setInterval method. I can emulate the same by having some global variable and calling the method of this global variable in setInterval, but i wanted to know if this is possible using the method directly.

最好的问候,凯沙夫

推荐答案

是的,您可以这样做.您需要一个辅助函数来创建一个 函数来绑定"现有对象:

Yes, you can do this. You need a helper function to make a new function that has your existing object "bound":

var someRandomObject = {
  someMethod: function() {
    // ... whatever
  },
  // ...
};

// this is a "toy" version of "bind"
function bind(object, method) {
  return function() {
    method.call(object);
  };
}

var interval = setInterval(bind(someRandomObject, someRandomObject.someMethod), 1000);

现在,当间隔计时器调用您的方法(someMethod")时,this"指针将引用该对象.

Now when the interval timer calls your method ("someMethod"), the "this" pointer will reference the object.

那个版本的绑定"被简化了.Prototype、Functional、jQuery 等库通常提供更健壮的版本.此外,绑定"函数有朝一日将成为 Javascript 的本机部分 —它已经在一些浏览器中.

That version of "bind" is simplified. Libraries like Prototype, Functional, jQuery, etc generally provide more robust versions. Additionally, the "bind" function will be a native part of Javascript someday — it already is in some browsers.

这篇关于使用 window.setInterval 在现有对象上执行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆