我有一个 debounce
函数,例如 var debounced = debounce(my_func, delay);
debounce
函数确保:
- 在延迟期间,
my_func
只能执行一次 my_func
将不会早于delay
ms 被调用
所以这里是:
var debounce = function(fn, delay) {
var scheduled;
return function() {
var that = this; // save context
console.log('this = ' + that);
if (!scheduled) {
scheduled = true;
setTimeout(function() {
scheduled = false;
//PROBLEM: `that` variable is always the same as on the first function call
console.log('executing... \nthis = ' + that);
fn.apply(that); //call function in saved context
}, delay);
}
}
}
测试:
var ctx;
var debounced = debounce(function() {
ctx = this;
}, 10);
debounced.call(11);
debounced.call(22); // PROBLEM: it leads to function invoked with this == 11 instead of this == 22
打印到控制台
"this = 11"
"this = 22"
"executing...
this = 11" // INSTEAD OF "this = 22"
最佳答案
你可以尝试这样的事情:
var debounce = function(fn, delay) {
var that = {};
var scheduled, last_fn;
return function() {
that.a = this;
console.log('this = ' + that.a);
if (!scheduled) {
scheduled = true;
setTimeout(function() {
scheduled = false;
console.log('executing... \nthis = ' + that.a);
fn.apply(that);
}, delay);
}
};
};
关于javascript - setTimeout 以奇怪的方式使用闭包上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708526/