简体   繁体   English

使用window.setInterval在现有对象上执行方法

[英]execute a method on an existing object with window.setInterval

Is it possible to run the method on an existing object on timeout of window.setInterval method. 是否可以在window.setInterval方法超时时在现有对象上运行该方法。 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. 我可以通过具有一些全局变量并在setInterval中调用此全局变量的方法来模拟相同的对象,但是我想知道是否可以直接使用该方法。

Best Regards, Keshav 最诚挚的问候,凯沙夫

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

Now when the interval timer calls your method ("someMethod"), the "this" pointer will reference the object. 现在,当间隔计时器调用您的方法(“ someMethod”)时,“ this”指针将引用该对象。

That version of "bind" is simplified. 该版本的“绑定”已简化。 Libraries like Prototype, Functional, jQuery, etc generally provide more robust versions. 像Prototype,Functional,jQuery之类的库通常提供更强大的版本。 Additionally, the "bind" function will be a native part of Javascript someday — it already is in some browsers. 另外,有一天,“绑定”功能将成为Javascript的本机部分-在某些浏览器中已经存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM