且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用箭头函数与||操作者

更新时间:2023-02-17 09:52:04

它失败,因为这只是无效的语法。 / 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.