[英]Why does accessing a property directly on an Object literal throw a SyntaxError?
When trying to access the property a
of the object {}
当试图访问属性a
对象的{}
{}.a
I get the error 我收到了错误
SyntaxError: Unexpected token .
With parens all is fine: parens一切都很好:
({}).a
Why do I get an error in the fist place? 为什么我在第一个地方出错? Is there ambiguity? 有歧义吗?
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. 您不能使用左大括号开始表达式语句。
The specification states: 规范说明:
NOTE An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block . 注意 ExpressionStatement不能以开括号大括号开头,因为这可能使其与Block不一致 。 Also, an ExpressionStatement cannot start with the
function
keyword because that might make it ambiguous with a FunctionDeclaration . 此外, ExpressionStatement不能以function
关键字开头,因为这可能使其与FunctionDeclaration不一致 。
Source: http://es5.github.com/x12.html#x12.4 资料来源: http : //es5.github.com/x12.html#x12.4
the {} are there to build the object. {}是用来构建对象的。 usually you first assign the new object to a variable. 通常,您首先将新对象分配给变量。
var o = {
a: "b"
};
console.log(o.a);
but this is also possible: 但这也是可能的:
console.log({
a: "b"
}.a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.