为什么直接在Object文字上访问属性会抛出一个SyntaxError? [英] Why does accessing a property directly on an Object literal throw a SyntaxError?
问题描述
当试图访问该对象的属性 a
{}
When trying to access the property a
of the object {}
{}.a
我得到错误
SyntaxError: Unexpected token .
随着parens一切正常:
With parens all is fine:
({}).a
为什么我会收到错误在第一个地方?有歧义吗?
Why do I get an error in the fist place? Is there ambiguity?
推荐答案
花括号被解释为block语句,而不是对象文字。你不能用左大括号开始一个表达式语句。
The curly braces are interpreted as a block statement, not as an object literal. You cannot begin an expression statement with a left curly brace.
规范声明:
注意 ExpressionStatement 无法以大括号
开头,因为这可能会使 Block 模糊不清。另外,
ExpressionStatement 不能以函数
关键字开头,因为
可能会使 FunctionDeclaration模糊不清。
NOTE An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the
function
keyword because that might make it ambiguous with a FunctionDeclaration.
来源: http://es5.github.com/x12.html#x12.4
这篇关于为什么直接在Object文字上访问属性会抛出一个SyntaxError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!