上下文丢失.设置超时

Loss of context. setTimeout

本文关键字:超时 设置 上下文      更新时间:2023-09-26
Function.prototype.defer = function(ms) {
    var self = this;
    return function() {
        setTimeout(self, ms);
    };
}
function f(a, b) {
    alert(a + b);
}
f.defer(5000)(1, 2); // 3

应该在 3 秒内显示数字 5,但不知何故推断出 NaN。

defer返回的函数不接受任何参数,因此忽略12

如果你想使用它们,那么你需要捕获它们并对它们做一些事情。

Function.prototype.defer = function(ms) {
    var self = this;
    return function(x, y) {
        setTimeout(self.bind(this, x, y), ms);
    };
}
function f(a, b) {
    alert(a + b);
}
f.defer(5000)(1, 2); // 3

这是因为您传递setTimeout函数,但参数1, 2未绑定到该函数,因此它调用f时没有参数。

你可以这样修复它:

Function.prototype.defer = function(ms) {
    var self = this;
    return function() {
        var args = arguments,
            context = this;
        setTimeout(function() {
            self.apply(context, args);
        }, ms);
    };
}
function f(a, b) {
    alert(a + b);
}
f.defer(5000)(1, 2); // 3