问题
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"}
回答1:
Given that you are using an ES6 for of loop, you already have block scope for your iteration variable anyway - just don't forget to use a let/const declaration! There is no need for an IEFE.
let x = {};
for (let i of ['a', 'b'])
x[i] = function() { this.v = i; };
If you don't use ES6, I'd recommend to use one of the Array iteration methods, like
var x = ['a', 'b'].map(function(i) {
return function() { this.v = i; };
});
来源:https://stackoverflow.com/questions/33463505/what-is-the-shortest-possible-way-to-write-a-block-scope-in-javascript