someOperation.then(function(x) {
things.forEach(function(thing) {
//doing something with 'thing' that depends on variable 'x'
});
});
在上面的代碼中,如何在回調函數中使變量'x'可用?或者我必須回到這種情況下使用for循環?將參數傳遞給Array.forEach回調函數
someOperation.then(function(x) {
things.forEach(function(thing) {
//doing something with 'thing' that depends on variable 'x'
});
});
在上面的代碼中,如何在回調函數中使變量'x'可用?或者我必須回到這種情況下使用for循環?將參數傳遞給Array.forEach回調函數
它是可用的。
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>
好的我改變了一下我的代碼。我仍然可以訪問x作爲閉包嗎? – AyushISM
@AyushISM是的,你還在。我添加了一個使用參數的例子。它的工作原理是一樣的。你可以通過在自己的代碼中使用'console.log(x)'來證明這一點。 –
您可以通過一個 「thisArg」 作爲第二個參數的forEach因此,例如:
let x = { a: 123 };
things = ['foo', 'bar']
things.forEach(function(thing) {
alert(this.a + thing);
}, x);
可能會根據你正在嘗試做的是有益的。
你有權訪問x作爲關閉 –
@ Gonzalo.-好的,我改了一下我的代碼。我仍然可以訪問x作爲閉包嗎?因爲當我在forEach回調函數中放置一個斷點時,在閉包列表中看不到'x'。 – AyushISM
被列在該列表中,您必須實際將其用作封閉。如果不是的話,你的js宇宙的所有變量都是可訪問的。只需在你的函數中使用它(即打印它與console.log),你會看到它列出 –