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
應該在5秒內顯示數字3,但以某種方式推斷出NaN。損失的上下文。 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
應該在5秒內顯示數字3,但以某種方式推斷出NaN。損失的上下文。 setTimeout
這是因爲,您將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
確定。我都明白了。非常感謝你! – Aleksandr
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
您還沒有傳遞的參數一起 – epascarello