() brackets, what does it do in the statement of ({__proto__: []} instanceof Array) in JavaScript

前端 未结 1 1429
感动是毒
感动是毒 2021-01-19 05:31

In JavaScript, the following gives an error:

相关标签:
1条回答
  • 2021-01-19 06:22

    When the interpreter sees a {, by default, it will think that you're declaring a new block, such as

    {
      console.log('foo');
    }

    As a result:

    {
      __proto__: []
    } instanceof Array

    doesn't make much sense - you can't instanceof a block.

    But when it's wrapped in parentheses, the interpreter knows to expect a value inside the parentheses, not a block - so it evaluates everything inside as an expression instead, and (properly) parses { __proto__: [] } as an object.

    This is exactly the same reason why, when destructuring to already assigned variables, you have to put parentheses around the line:

    let x, y;
    ({x, y} = { x: 'foo', y: 'bar'});
    console.log('done ' + x);

    works, but it doesn't without the ():

    let x, y;
    {x, y} = { x: 'foo', y: 'bar'};
    console.log('done ' + x);

    0 讨论(0)
提交回复
热议问题