What is the shortest possible way to write a block

2019-09-06 13:32发布

问题:

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.ax.(anonymous function) {v: "a"}
new x.bx.(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.ay.(anonymous function) {v: "b"}
new y.by.(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; };
});