简体   繁体   English

不明白为什么不应该在语句开头使用对象文字

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

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." 在Mozilla上阅读了一些JS tutu并遇到了以下语句:“您不应在语句的开头使用对象文字。这将导致错误或行为不符合您的预期,因为{将被解释为块的开始。”

I don't understand what they mean. 我不明白他们的意思。 Could someone shed some light on this please 有人能对此有所启发吗

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. (*)好吧,这不是必须的,它可以向前看是否该块的其余部分看起来像是对象文字或代码,但是消除两者的歧义会使解析器复杂得多,因此定义了语言因此不必这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM