What is the shortest possible way to write a block scope in JavaScript?

守給你的承諾、 提交于 2019-12-12 02:49:38

问题


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; };
});


来源:https://stackoverflow.com/questions/33463505/what-is-the-shortest-possible-way-to-write-a-block-scope-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!