someOperation.then(function(x) {
things.forEach(function(thing) {
//doing something with 'thing' that depends on variable 'x'
});
});
在上面的代码中,如何在回调函数中使变量'x'可用?或者在这种情况下我是否必须回到使用for循环?
答案 0 :(得分:1)
您可以将“thisArg”作为第二个参数传递给forEach,例如:
let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
alert( this.a + thing );
}, x);
根据您的目的,可能会有所帮助。
答案 1 :(得分:0)
可用。
let x = {
name: 'Mike'
};
['Hello', 'Goodbye'].forEach(function(greeting) {
document.querySelector('pre').innerHTML += greeting + ', ' + x.name + '\n';
});
<pre></pre>
您在此处使用的内容称为closure,是Javascript的常用功能。基本上,任何函数都可以访问其父作用域中的任何其他变量。
function log(msg) {
document.querySelector('pre').innerHTML += msg + '\n';
}
var global = 'global';
function firstLevel(third) {
var first = 'first';
// `global` is in the parent scope so we can access it
log(global + ' -> ' + first);
function secondLevel() {
var second = 'second';
// Same thing with `first` here
log(global + ' -> ' + first + ' -> ' + second);
// This even works with passed in arguments
log(global + ' -> ' + first + ' -> ' + second + ' -> ' + third);
// We can even change closed over variables
first = 'fourth?';
}
secondLevel();
log(first); // Notice that `first` changed.
}
log(global);
firstLevel('third'); // Notice how `third` is used in `secondLevel`
<pre></pre>