Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

javascript - Immediately accessing an object's property

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's not ignored, it's just not recognized as an object here.

{ ... } at the start of a statement is parsed as a Block[spec] of code.

In the case of {foo: 'bar'}.foo, the inner code foo: "bar" is parsed as a LabelledStatement[spec].

So {foo: 'bar'} parses correctly (even if it doesn't do what you expect) but the property access syntax is actually causing the syntax error, as accessing a property on a block is not valid.


As you noticed the solution is to enclose the object in parentheses:

({foo: 'bar'}).foo

Starting the statement with ( causes the parser to search for an expression inside of the parentheses. {foo: 'bar'} when parsed as an expression is an Object Initializer[spec], as you expected.


For {foo: 'bar'}['foo'], it's actually parsed as two separate statements: a block ({foo: 'bar'} and an Array initializer (['foo']):

{foo: 'bar'};
['foo'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...