【发布时间】: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