简体   繁体   中英

Why can't I directly access a property of an object literal?

Why the following syntax

{a:1,b:2}.constructor

is invalid, whereas

[1,2].constructor 

is valid?

{a:1,b:2}.constructor is not invalid syntax, but it is ambiguous, because {} denotes a block, or an object? So you have to disambiguate the expression with parentheses, like ({a:1,b:2}).constructor . Now JavaScript knows you meant to use an object.

If you use that syntax in a context where it is clearly an object, then there is no ambiguity:

console.log({a:1,b:2}.constructor) // works fine

Curve brackets at the start of a line is recognized as a code block instead of an object literal .

If you look at the error in the console, you can see Uncaught SyntaxError: Unexpected token : . So, the error is not in calling the constructor property.

Also, when you write in the console

{a:1}

JS interprets this as a block with a label and not an object with property a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM