From Introduction to ES6 Standards (3rd Edition) :

Destruct assignment of an object is shorthand for:

    let { foo: foo, bar: bar } = { foo: 'aaa', bar: 'bbb' }
Copy the code

That is, the internal mechanism for deconstructing assignment of an object is to find the property of the same name and then assign it to the corresponding variable. It is the latter, not the former, that is really assigned.

    let { foo: baz } = { foo: 'aaa', bar: 'bbb' }
    baz // 'aaa'
    foo // error: foo is not defined
Copy the code

In the code above, foo is the matching pattern and Baz is the variable. The variable that is actually assigned is baz, not pattern foo.

Like arrays, deconstruction can also be used for nested structured objects.

    let obj = {
        p: ['Hello', { y: 'World'}}]let { p: [x, { y }] } = obj
    x // Hello
    y // World
Copy the code

Note that p is a mode, not a variable, and therefore will not be assigned. If p is also assigned as a variable, it can be written as follows:

    let obj = {
        p: ['Hello', { y: 'World'}}]let { p, p:[x, { y }] } = obj
    x // Hello
    y // World
    p // ['Hello', { y: 'World' }]
Copy the code

Here’s another example:

var node = { loc: { start: { line: 1, column: 5 } } } var { loc, loc: { start }, loc: {start: {line}}} = node line // 1 loc // Object {start: Object} start // Object {line: 1, column: 5}Copy the code

The above code has three deconstruction assignments, namely the deconstruction assignments of loc, start and line. Note that in the last deconstruction assignment of the line attribute, only line is a variable, loc and start are modes, not variables.

The rule for deconstructing assignment is to turn the value to the right of the equals sign into an object whenever it is not an object or array. Because undefined and NULL cannot be converted to an object, they both report errors when destructively assigned.

let { prop: x } = undefined; // TypeError
let { prop: y } = null; // TypeError
Copy the code