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

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

问题描述

在我的代码中,我有一些东西可以归结为:

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

推荐答案

这是正常的.与 function 表达式不同,后者是 PrimaryExpression 像其他文字和标识符一样,特别是箭头函数是 AssignmentExpression 并且只能出现在分组、逗号、赋值、条件(三元)和产量表达式中.任何其他运算符都会导致歧义.

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.

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

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