简体   繁体   English

为什么直接在Object文字上访问属性会抛出一个SyntaxError?

[英]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.

相关问题 为什么会抛出一个SyntaxError? - Why does this throw a SyntaxError? 为什么我不能直接访问对象文字的属性? - Why can't I directly access a property of an object literal? JavaScript 访问文字 object 属性 - JavaScript Accessing literal object property 为什么访问布尔值的属性不会引发错误-javascript - why does accessing a property of a boolean value not throw an error - javascript 为什么在Internet Explorer中访问localStorage对象会抛出错误? - Why does accessing the localStorage object in Internet Explorer throw an error? 尝试解析简单的json对象时,为什么JSON.parse()抛出Uncaught SyntaxError:Unexpected token? - Why does JSON.parse() throw Uncaught SyntaxError: Unexpected token when trying to parse a simple json object? 为什么在一个对象的一个​​属性中引用同一对象的另一个属性中的jQuery选择器会引发错误? - Why does referencing a jQuery selector in one property of an object, from another property of the same object throw an error? 为什么gulp-sprite-generator会抛出“ SyntaxError:意外令牌;”? - Why does gulp-sprite-generator throw “SyntaxError: Unexpected token ;”? 为什么在三元运算符内部返回会抛出 SyntaxError? - Why does returning inside the ternary operator throw a SyntaxError? 为什么在try块中重新声明函数标识符会抛出SyntaxError? - Why does redeclaring a function identifier within a try block throw a SyntaxError?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM