为什么逻辑或运算符(||)带有空箭头函数(()=> {})会导致语法错误? [英] Why does the logical or operator (||) with an empty arrow function (()=>{}) cause a SyntaxError?

查看:329
本文介绍了为什么逻辑或运算符(||)带有空箭头函数(()=> {})会导致语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我有一些归结为:

In my code, I have something that boils down to this:

var x = y || ()=>{};

(如果你想知道,我后来打电话给 x() y 可能被定义为函数,也可能没有,所以如果不是,我不想抛出TypeError。)

(In case you are wondering, I am later calling x() and y may be defined as a function or it might not, so I don't want a TypeError to be thrown if it is not.)

出于某种原因,这会导致

For some reason, this causes a


语法错误:意外的令牌)

SyntaxError: Unexpected token )

为什么?我发现

var x = y || (()=>{});

工作正常,但

y || ()=>{}

不能正常工作。这是推测,还是V8或Chrome中的错误? (我仅在Chrome稳定版的最新版本中对此进行了测试。)

dosen't work. Is this specced, or a bug in V8 or Chrome? (I tested this only in the latest release of Chrome stable.)

推荐答案

这是正常现象。与函数表达式不同,它是 PrimaryExpression 与其他文字和标识符一样,箭头功能特别是 AssignmentExpression 并且只能出现在分组,逗号,赋值,条件(三元)和yield表达式中。除此之外的任何其他运算符都会导致含糊不清。

This is normal. Unlike a function expression, which is a PrimaryExpression like other literals and identifiers, and arrow function specifically is an AssignmentExpression and can only appear inside grouping, comma, assignment, conditional (ternary) and yield expressions. Any other operator than those would lead to ambiguities.

例如,如果您希望 y || ()=> z 工作,然后()=> z || y 应该可以工作(假设对称优先)。然而,这显然与我们期望我们可以在箭头函数的简洁体内使用任何运算符相冲突。因此,这是一个语法错误,需要明确的分组才能工作并保持可维护状态。

For example, if you expect y || ()=>z to work, then also ()=>z || y should be expected to work (assuming symmetric precedence). That however clearly collides with our expectation that we can use any operators inside concise bodies of arrow functions. Therefore, it's a syntax error and requires explicit grouping to work and stay maintainable.

这篇关于为什么逻辑或运算符(||)带有空箭头函数(()=> {})会导致语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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