Given these four examples of defining an object and then attempting to immediately access their properties:
{foo: 'bar'}.foo
// syntax error: unexpected_token
I expected this would return the value of 'foo', but it results in a syntax error.
The only explanation I can come up with is that the object definition hasn't been executed and therefore is not yet an object. It seems that the object definition is therefore ignored and the syntax error comes from attempting to execute just:
.foo
// results in the same syntax error: unexpected_token
Similarly:
{foo: 'bar'}['foo']
// returns the new Array ['foo']
Which seems to be evidence that the object literal is ignored and the trailing code is executed.
These, however, work fine:
({foo: 'bar'}).foo
// 'bar'
({foo: 'bar'})['foo']
// 'bar'
The parentheses are used to run the line of code and since the result of that parenthetical operator is the instantiated object, you can access properties.
So, why is the object definition ignored and not executed immediately?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…