Destructure and assign to new variable at the same

2019-08-26 01:30发布

问题:

I am trying to destructure object and assign it to new variable at the same time:

let {x} = a = {x: 'cool'};
console.log(a, x);

which outputs:

//Object { x: "cool" } cool - in Firefox
//ReferenceError: a is not defined - in Chrome, babel-node

Why is there difference and what is the correct behavior?

UPDATE:

This is maybe more generic use case. While this works in all environments:

var a = b = {x: 'cool'};

this statement is not working in chrome/babel-node:

var {x} = a = {x: 'cool'}; //SyntaxError: Unexpected token {

There is also different error message when using var instead of let.

回答1:

In your code, a is not defined. let a = b = c does not define b. You need to say

let a = {x: 1}, {x} = a;

Firefox doesn't support let, so I'm wondering how your example worked there at all. See https://kangax.github.io/compat-table/es6/.