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.a ⟹ x.(anonymous function) {v: "a"}
 new x.b ⟹ x.(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.a ⟹ y.(anonymous function) {v: "b"}
 new y.b ⟹ y.(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
Post a Comment