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

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

问题描述

使用Babel,我可以看到

  callback =()=> {}; 

编译为

 code> callback = function callback(){}; 

这是我期望的。但是,当我尝试使用 ||

  callback = callback || ()=> {} 

我期望相当于

  callback = callback ||功能(){}; 

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

解决方案

它失败,因为这只是无效的语法。 / p>

使用以下命令使其工作:

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

如果你不这样包装,被解释为您键入以下内容。但是这是无效的语法。

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

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


Using Babel, I can see that

 callback = () => {};

compiles to

callback = function callback() {};

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

callback = callback || () => {}

Which I'd expect to be equivalent to

 callback = callback || function(){};

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 || ()) => {}

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天全站免登陆