What difference does it makes to parse something as an object literal rather than as a block?

前端 未结 2 1231
刺人心
刺人心 2021-01-28 23:51

Sorry for my ignorance on JavaScript basic concepts.

It boils down to this:

Literal - A value found directly in the script. Examples:

2条回答
  •  温柔的废话
    2021-01-29 00:29

    A group that begins with a { and ends with a } is treated as either object literal or a block depending on context*.

    Within an expression context the group is interpreted as an object literal. Writing a block within an expression context will generate a syntax error:

    // Valid code:
    foo = {a:b};
    ({a:b});
    
    // Syntax errors:
    foo = {var a = b};
    ({var a = b});
    

    Outside of an expression context the group is interpreted as a block. Depending on exactly how the code is written, an object literal written outside of an expression context is either a syntax error or will be interpreted as a label.

    *note: In the ECMAscript spec the word "context" is used to mean something specific. My use of the word here is with the general meaning in computer science with regards to parsing.

提交回复
热议问题