execute a method on an existing object with window.setInterval

吃可爱长大的小学妹 提交于 2019-12-13 07:04:57

问题


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.

Best Regards, Keshav


回答1:


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.



来源:https://stackoverflow.com/questions/3044478/execute-a-method-on-an-existing-object-with-window-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!