Don't understand why you should not use an object literal at the beginning of a statement

后端 未结 1 1226
走了就别回头了
走了就别回头了 2021-01-26 14:37

Just reading some of the JS tuts on Mozilla and came across the statement \"You should not use an object literal at the beginning of a statement. This will lead to an error or n

相关标签:
1条回答
  • 2021-01-26 15:32

    An object literal starts with {

    { name: "Paul" age: 30 } // I wish
    

    But so does a block.

    { if (age < 30) console.log ("He's lying again"); }
    

    When the interpreter sees "{" it has to pick one interpretation (*). It picks "block" and tries to parse your object literal as if it was code. Which it isn't and so things quickly go wrong.

    (*) Well, it doesn't have to, it could look ahead to see if the rest of the block looks like an object literal or code, but disambiguating the two would make the parser a lot more complicated, so the language is defined so it doesn't have to do this.

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