execute a method on an existing object with window

2019-09-15 05:32发布

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条回答
放我归山
2楼-- · 2019-09-15 06:06

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.

查看更多
登录 后发表回答