JS 什么时候将 {} 解释为空块而不是空对象? [英] When does JS interpret {} as an empty block instead of an empty object?
问题描述
我正在阅读这个:
声明:堵塞变量语句空语句表达式语句……很多其他的东西……
语句可以是块、变量语句、空语句、表达式语句或许多其他东西,这是一种非常奇特的说法.请注意,第一个选项有一个阻止":
块:{ 语句列表(选择)}声明清单:陈述StatementList 语句
这又是一种奇特的说法,表示一个块是一个 {
,可选地后跟一堆语句,后跟一个 }
.
这就是您在示例中看到的内容:在 JavaScript 解析器认为您拥有的可能是对象字面量之前(在 ExpressionStatement
下的某处定义,Statement"的第四件事可能是),它首先认为你有一个块".
如果你愿意,你可以在 JavaScript 引擎的源代码中看到它:
- 在 V8 中,Chrome 的 JavaScript 引擎,我们进入
Parser::ParseStatement
.首先检查是我们是否重新在{
上,如果是,则解析为块. - 在 Firefox 的 JavaScript 引擎 SpiderMonkey 中,我们从
Parser::statement
再次看到 第一次检查针对{
并将其解析为块语句.
关于您的第二个问题,关于这个问题已详细介绍.用一句话总结:Node.js 将您的输入视为表达式(因此它不能是块"),而 Firebug/Chrome 开发工具将其视为语句".
I was reading the answer to this question (about the "wat" video) and it said:
{}+[]
This is interpreted as an empty block of code, unary plus and empty array. First part does nothing, array is converted to a comma-separated string of it's elements (empty string for empty array), then to a number (empty string is converted to 0), hence 0.
I am currently learning JS from "The Definitive Guide" so I try to really understand things like that.
My question is, when does JS decide to interpret {}
as an empty block of code, instead of an empty object?
Also, there are some inconsistencies between Node.js and Firebug which I would like to understand.
Firebug:
Node.js:
Let's look at the language grammar, shall we? Section 12, Statements:
Statement :
Block
VariableStatement
EmptyStatement
ExpressionStatement
...lots of other stuff...
That's a very fancy way of saying that a statement can be a block, a variable statement, an empty statement, an expression statement, or lots of other stuff. Notice that the first option there is a 'Block':
Block :
{ StatementList(opt) }
StatementList :
Statement
StatementList Statement
Which is again, a fancy way of saying that a block is a {
, optionally followed by a bunch of statements, followed by a }
.
And that's what you see in your example: Before the JavaScript parser thinks that what you have could be an object literal (which is defined somewhere under ExpressionStatement
, the 4th thing a 'Statement' could be), it first thinks that you have a 'Block'.
Edit: If you want, you can see it live in a JavaScript engine's source code:
- In V8, Chrome's JavaScript engine, we go into
Parser::ParseStatement
. The first thing it checks is whether we're on a{
, and if it does, parses as block. - In SpiderMonkey, Firefox's JavaScript engine, we go from
Parser::statement
to again see the first check being against a{
and parsing it as a block statement.
Regarding your second question, that's been covered to great detail on this question. To summarise in a sentence: Node.js treats your input as if it were an expression (thus it can't be a 'Block'), while Firebug/Chrome dev tools treat it like a 'Statement'.
这篇关于JS 什么时候将 {} 解释为空块而不是空对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!