函数作为对象键与块中标记函数之间的语法冲突 [英] Javascript Conflicting Syntax Between Function As Object Key And Labeled Function in Block

查看:94
本文介绍了函数作为对象键与块中标记函数之间的语法冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个同时支持标有标签的函数声明块语句,浏览器确定以下内容的标准方法/方法是:对象是具有名为L的属性的对象,该属性为函数F,还是包含标记为L的函数F的块:

Assuming you have a browser that supports both labeled function declarations and block statements, what is the standard way/method for browsers to determine if the following is an object with a property named L that is function F, or a block that contains function F labeled as L:

{
    L: function F(){}
}

例如

为了展示我的意思,以下是上述代码的两个不同副本,将其修改为将其展示为数组和函数:

E.g.

To expose what I mean, here are two different copies of the above code modified to expose it as an array and as a function:

document.body.textContent = typeof( () => {
    L: function F(){}
} )

在上面的代码中,浏览器识别出箭头功能符号并确定它是一个块语句.但是,

In the above code, the browser recognizes the arrow function notation and determines that it is a block statement. However,

document.body.textContent = typeof {
    L: function F(){}
}

上面的代码使浏览器认为它是写为对象文字的对象,其索引L为函数F

The above code makes the browser think that it is an object written out as an object literal with index L being function F

推荐答案

您可以将问题简化为:浏览器如何知道{是否启动,以及何时启动对象文字?

You can reduce the question to: How does the browser know whether { starts a block and when does it start an object literal?

其答案是,JS引擎将{视为在语句位置出现的块的开始,而将{视为在表达式位置出现的对象文字的开始.

And the answer to that is that JS engines will treat { as the start of a block if it appears in a statement position and as the start of an object literal if it is in an expression position.

这就是为什么当{}出现在语句位置但您想要一个对象时,必须在{}周围加上括号(())的原因.

That's the reason why you have to add parenthesis (()) around {} when they appear in a statement position but you want an object instead.

带标签的函数声明的引入根本不会改变情况,因为情况已经模棱两可了:

The introduction of labeled function declarations doesn't change the circumstances at all because the situation was already ambiguous:

{
  foo: 42
}


再次看一下规格,实际上指出了这种歧义:


Looking at the spec again, this ambiguity is actually pointed out:

ExpressionStatement 不能以U + 007B(左卷曲的括号)开头,因为它可能与(语法也反映了这一点)

(and the grammar reflects that too)

这篇关于函数作为对象键与块中标记函数之间的语法冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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