我在回调中遇到变量范围问题。这有点难以解释,所以这是我正在使用的简化代码。请注意,我使用的是 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),而是频率为 250 的相同音符 3 次。
我明白为什么(实际调用回调时 var freq
等于 250,但我不知道如何解决这个问题。有什么想法吗?
谢谢!
最佳答案
当您在循环中使用延迟回调时,您必须为此调用创建一个特殊的范围。 为此,您有两个主要解决方案:在类中创建一个函数或一个本地匿名函数,例如 (function(localVar) {/* 使用传递给此匿名函数的本地变量在此处运行延迟回调 */})(localVar) ;
这可以很容易地解释为您的回调正在使用循环的范围,si 对于每个循环,您的变量的值发生变化,并且当调用回调时,您的变量具有最后的值。
关于Javascript:回调中的变量范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40203808/