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

标签 javascript closures

我有一个 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/

相关文章:

javascript - 生成指定范围内的随机数——各种情况(int、float、inclusive、exclusive)

javascript - Polymer 1.0+ iron-image - 等待图像文件存在以避免 404 错误的最佳实践

javascript - 如何使用 AES-GCM 从 IE 11 加密操作的结果中解密数据

javascript - Kendo UI 默认网格过滤器值

function - 关闭不返回所需的输出

python - 将属性写入当前范围之上

javascript - React.js : Toggle className on click

c# - 关闭和引用设置

javascript - 带函数的 JavaScript 闭包是如何工作的?

file-io - 在 Common Lisp 中逐行(低内存)读取文件