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

余生长醉 提交于 2019-12-02 14:47:48

问题


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 not behave as you expect, because the { will be interpreted as the beginning of a block."

I don't understand what they mean. Could someone shed some light on this please


回答1:


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.



来源:https://stackoverflow.com/questions/26997647/dont-understand-why-you-should-not-use-an-object-literal-at-the-beginning-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!