上下文丢失.设置超时
Loss of context. setTimeout
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
返回的函数不接受任何参数,因此忽略1
和2
。
如果你想使用它们,那么你需要捕获它们并对它们做一些事情。
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
相关文章:
- 设置第一次执行的超时
- 当定位模式设置为“0”时,总是达到关于地理定位的超时;仅设备”;
- 为什么页面重新加载会使设置超时无效,以及如何避免
- 立即设置超时
- 如何设置$.ajax请求的超时,并在超时时间过长时进行重做
- iOS Safari Javascript设置超时问题
- 如何将嵌套设置超时转换为承诺
- 如何设置淡出或超时以提醒成功&露天矿2.2中的警告框
- 如何在量角器测试中设置$interval而不是超时
- 如何循环设置超时函数
- 关于设置超时/间隔上下文
- 清除设置超时之前的间隔将不起作用
- 在悬停功能中设置超时
- 延迟设置超时()
- 我们是否需要设置超时进行短轮询
- 如何在firefox-sdk中设置请求超时设置
- 将超时设置为layoutTemplate流星/铁
- Jquery将超时设置为selector
- 清除javascript对象中的超时设置
- MongoError:游标被杀死或超时-Meteor超时设置无效