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

前端 未结 2 1232
刺人心
刺人心 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:25

    First, don't eval JSON, use JSON.parse on the String source


    A block is a "group of expressions" for example,

    let x = 0;
    if (true) {
        // this is a block
        ++x;
    }
    

    However, equally this is also a block

    let x = 0;
    { // hi there, I'm a block!
        ++x;
    }
    

    This means when the interpreter sees block notation, it assumes a block even if you do something like this

    { // this is treated as a block
        foo: ++x
    }
    

    Here, foo acts as a label rather than a property name and if you try to do more complex things with the attempted object literal, you're going to get a Syntax Error.

    When you want to write an Object literal ambiguously like this, the solution is to force the interpreter into "expression mode" explicitly by providing parenthesis

    ({ // this is definately an Object literal
        foo: ++x
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题