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

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

In JavaScript, the following gives an error:

{ __proto__: [] } instanceof Array;

If I surround it in (brackets) it has no error:

({ __proto__: [] } instanceof Array);

Why is this?

回答1:

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);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!