gpt4 book ai didi

javascript - setTimeout 以奇怪的方式使用闭包上下文

转载 作者:行者123 更新时间:2023-12-02 15:54:03 24 4
gpt4 key购买 nike

我有一个 debounce 函数,例如 var debounced = debounce(my_func, delay);

debounce 函数确保:

  1. 在延迟期间,my_func 只能执行一次
  2. my_func 将不会早于 delay ms
  3. 被调用

所以这里是:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com