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


is shortest possible way block scope in body of for loop?

x = {}; (i of ['a', 'b']) {   (function(i) {     x[i] = function() { this.v = i; }   })(i); } 

or there syntactic sugar not able find?

explanation:

with block scope created objects have different values.

new x.ax.(anonymous function) {v: "a"}
new x.bx.(anonymous function) {v: "b"}

without block scope

y = {}; (i of ['a', 'b']) {   y[i] = function() { this.v = i; } } 

the created objects have same value.

new y.ay.(anonymous function) {v: "b"}
new y.by.(anonymous function) {v: "b"}

given using es6 for of loop, have block scope iteration variable anyway - don't forget use let/const declaration! there no need iefe.

let x = {}; (let of ['a', 'b'])     x[i] = function() { this.v = i; }; 

if don't use es6, i'd recommend use 1 of array iteration methods, like

var x = ['a', 'b'].map(function(i) {     return function() { this.v = i; }; }); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -