如何在 || 中使用箭头函数操作员 [英] How to use arrow function with || operator

查看:28
本文介绍了如何在 || 中使用箭头函数操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Babel,我可以看到

Using Babel, I can see that

 callback = () => {};

编译为

callback = function callback() {};

这正是我所期望的.但是,当我尝试将它与 ||

which is what I expect. However I get an error when I try to use it with ||

callback = callback || () => {}

我期望相当于

 callback = callback || function(){};

为什么这是一个错误?另外,这个熟悉的语法有没有更正确的 ES6 版本?

Why is this an error? Also, is there a more correct ES6 version of this familiar syntax?

推荐答案

它失败了,因为那只是无效的语法.

It fails because that is just not valid syntax.

使用以下方法使其工作:

Use the following to make it work:

callback = callback || (() => {})

如果你不这样包装它,它会被解释为你输入了以下内容.但这是无效的语法.

If you don't wrap it that way, it would be interpreted as if you typed the following. But that is invalid syntax.

callback = (callback || ()) => {}

要扩展分配的评估,请参阅AssignmentExpression.它由一个 ConditionalExpression 或一个 ArrowFunction(或其他一些我将忽略的表达式)组成.所以解释器会尝试使用你的代码作为条件.但是 () 本身在该上下文中是无效的,因为在 ParenthesizedExpression内部需要一个表达式.结果,它将失败.如果您改为将表达式分组为 callback ||(() => {}) LogicalOrExpressions 的两边都是有效的表达式.

To extend on the evaluation of the assignment, see the specification of the AssignmentExpression. It consist of a ConditionalExpression or an ArrowFunction (or some other expressions I will disregard). So the interpreter will try to use your code as a conditional. But the () itself is not valid in that context as an expression is expected inside that ParenthesizedExpression. As a result, it will fail. If you instead group the expression as callback || (() => {}) both sides of the LogicalOrExpressions are valid expressions.

这篇关于如何在 || 中使用箭头函数操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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