Is this the shortest possible way to get a block scope in the body of the for
loop?
x = {};
for (i of ['a', 'b']) {
(function(i) {
x[i] = function() { this.v = i; }
})(i);
}
Or is there any syntactic sugar I am not able to find?
Explanation:
With block scope the created objects have different values.
new x.a
⟹ x.(anonymous function) {v: "a"}
new x.b
⟹ x.(anonymous function) {v: "b"}
Without block scope
y = {};
for (i of ['a', 'b']) {
y[i] = function() { this.v = i; }
}
the created objects will have the same value.
new y.a
⟹ y.(anonymous function) {v: "b"}
new y.b
⟹ y.(anonymous function) {v: "b"}