How to Destructure All Properties into the Current Scope/Closure in Es2015

How do I destructure all properties into the current scope/closure in ES2015?

I think you're looking for the with statement, it does exactly what you are asking for:

const vegetableColors = {corn: 'yellow', peas: 'green'};
with (vegetableColors) {
console.log(corn);// yellow
console.log(peas);// green
}

However, it is deprecated (in strict mode, which includes ES6 modules), for good reason.

destructure all properties into the current scope

You cannot in ES61. And that's a good thing. Be explicit about the variables you're introducing:

const {corn, peas} = vegetableColors;

Alternatively, you can extend the global object with Object.assign(global, vegetableColors) to put them in the global scope, but really, that's worse than a with statement.

1: … and while I don't know whether there is a draft to allow such things in ES7, I can tell you that any proposal will be nuked by the TC :-)

ES2015 Destructure object twice in same scope

You can wrap the assignment in parens to reassign the variables via destructuring. The reason this is necessary is because otherwise the { is assumed by the parser to begin a block rather than an object literal or assignment pattern. This blog post explains the situation in more detail.

function(oldState, newState) {
let {foo, bar} = oldState;
// do stuff //
({foo, bar} = newState);
}

How to destructure into dynamically named variables in ES6?

Short answer: it's impossible and it won't be possible.

Reasoning behind this: it would introduce new dynamically named variables into block scope, effectively being dynamic eval, thus disabling any performance optimization. Dynamic eval that can modify scope in fly was always regarded as extremely dangerous and was removed from ES5 strict mode.

Moreover, it would be a code smell - referencing undefined variables throws ReferenceError, so you would need more boilerplate code to safely handle such dynamic scope.



Related Topics



Leave a reply



Submit