将setTimeout()包装器实现为Element.prototype中的方法



我正在尝试向Element.prototype添加一个方法,该方法将通过系统setTimeout()调用与当前对象具有相同this的用户函数。我的实现如下:

Element.prototype.timeout =
    function (func, delay)
    {
        var that = this;
        return setTimeout(function () { func.call(that) }, delay);
    }

有没有更有效或更优雅的方法来做到这一点?

(请不要jQuery)

如果你真的想避免lambda函数,你可以做一些类似的事情:

Function.prototype.delay = function (delay, context) {
  this.self = context;
  this.args = Array.prototype.slice.call(arguments, 2);
  return setTimeout(this, delay);
};
(function () {
  var self = arguments.callee.self || this;
  var args = arguments.callee.args || Array.prototype.slice.call(arguments);
  alert(args[0]);
}).delay(1500, null, 42);

但这样做很难看。

我能想到的唯一一件事就是让它成为一个像这样的实用函数,可以与任何对象上的任何函数或方法一起使用:

function delayMethod(obj, method, delay) {
    setTimeout(function() {
        method.call(obj);
    }, delay);
}

或者,通过可变数量的参数更具可扩展性:

function delayMethod(obj, method, delay /* args to method go here */) {
    var args = [].slice.call(arguments, 3);
    setTimeout(function() {
        method.apply(obj, args);
    }, delay);
}

最新更新