I am not sure if it's related to closure or it's related to JS call by assigning and hope someone could help clarify this.
The expected result below is to print A, B, C separately.
I guess the reason it's not working is that when the function added to array is executed, the name variable inside the function points to value C so the result is C,C,C not A,B,C
Then I tried to use IIFE to encapsulate(not sure if it's the right word) name variable and it works.
But what confuses me is that I thought the primitive variable should have passed value instead of reference? Or it is not the cause for this outcome and related to something else (maybe mysterious closure)?
This is not working
let names = ["A", "B", "C"];
let targetPages = [];
function setName() {
for (var name of names) {
targetPages.push(function() {
console.log(name);
});
};
};
setName();
for (var f in targetPages) {
targetPages[f]();
}
This is working.
let names = ["A", "B", "C"];
let targetPages = [];
function setTarget() {
for(var name of names) {
(function(n) {
targetPages.push(function() {
console.log(n);
});
}(name));
};
};
setTarget();
for(var f in targetPages) {
targetPages[f]();
}