【问题标题】:Javascript: variable scope in callback? [duplicate]Javascript:回调中的变量范围? [复制]
【发布时间】:2016-10-23 14:07:12
【问题描述】:

我对回调中的变量范围有疑问。这有点难以解释,所以这是我正在使用的简化代码。请注意,我使用的是 ES6。

class Foo {
    constructor() { /* ... */ }

    // Execute 'callback' after 'delay' has passed (works fine)
    timer(delay, callback) { /* ... */ }

    // Emit a sound of 'frequency' for 'duration' (works fine)
    sound(duration, frequency) { /* ... */ }

    // Play each 'frequency' for 'duration'
    music(duration, frequencyArray) {
        var that = this;
        for (var i = 0; i < frequencyArray.length; i++) {
            var freq = frequencyArray[i];
            this.timer(duration*i, function() {
                // The line below doesn't work properly
                // 'freq' is always equal to the last value of the array
                that.sound(duration, freq); 
            });
        }
    }
}

// Usage
var F = new Foo();
F.music(200, [150, 200, 250]);

在上面的例子中,我没有听到 3 个不同的音符(150、200、250),而是听到 3 次频率为 250 的相同音符。

我明白为什么(实际调用回调时,var freq 等于 250,但我不知道如何解决这个问题。知道吗?

谢谢!

【问题讨论】:

    标签: javascript scope callback ecmascript-6


    【解决方案1】:

    当您在循环中使用延迟回调时,您必须为此调用创建一个特殊范围。 为此,您有两个主要解决方案:在您的类中创建一个函数或一个本地匿名函数,例如 (function(localVar) { /* 使用传递给此匿名函数的局部变量在此处运行延迟回调 */ })(localVar) ;

    这很容易解释为你的回调使用循环的范围,每个循环的 si,你的变量的值发生变化,当回调被调用时,你的变量具有最后一个值。

    【讨论】:

      猜你喜欢
      • 2014-10-27
      • 2015-06-14
      • 2013-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多