我正在尝试向 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);
但是这样做很丑陋。
关于javascript - 将 setTimeout() 包装器实现为 Element.prototype 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12207437/