不明白为什么不应该在语句的开头使用对象文字 [英] Don't understand why you should not use an object literal at the beginning of a statement

查看:73
本文介绍了不明白为什么不应该在语句的开头使用对象文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需阅读一些 JS tuts on Mozilla 并且遇到了声明你不应该在语句开头使用对象文字。这将导致错误或不按预期行事,因为{将被解释为一个街区。

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

推荐答案

对象文字以{

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

但块也是如此。

{ 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.

这篇关于不明白为什么不应该在语句的开头使用对象文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆