开发者

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. I can emulate the same by having some global variable and calling the method of thi开发者_StackOverflow社区s global variable in setInterval, but i wanted to know if this is possible using the method directly.

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜