Immediately accessing an object's property

后端 未结 2 1313
误落风尘
误落风尘 2020-12-21 04:36

Given these four examples of defining an object and then attempting to immediately access their properties:

{foo: \'bar\'}.foo
// syntax error: unexpected_to         


        
2条回答
  •  既然无缘
    2020-12-21 05:31

    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'];
    

提交回复
热议问题