Don't understand why you should not use an obj

2020-05-09 01:32发布

问题:

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.