javascript - 为什么我不能返回箭头函数?

标签 javascript ecmascript-6 higher-order-functions arrow-functions

<分区>

我这里有一个高阶排序函数。

虽然这按预期工作:

var square = (a) => a * a;

var callAndLog = (func) => {
  return function () {
    var res = func.apply(undefined, arguments);
    console.log("Result is: " + res);
    return res;
  }
};

var squareAndLog = callAndLog(square);

squareAndLog(5);  // Result is 25

这里,当我返回一个箭头函数时,它不起作用:

var square = (a) => a * a;
var callAndLog = (func) => {
  return (() => {
    var res = func.apply(undefined, arguments);
    console.log("Result is: " + res);
    return res;
  })
};
var squareAndLog = callAndLog(square);
squareAndLog(5); // Result is NaN

我知道箭头函数是松散的,这就是为什么我在这里尝试在括号 () 中返回它。没有它们也行不通。

最佳答案

来自 MDN :

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

箭头函数不会将 arguments 对象绑定(bind)到它们的主体。您的函数依赖于 arguments 的使用,因此它不能用作箭头函数。

正如上面评论中所建议的,您可以使用 ...args 代替:

var square = (a) => a * a;
var callAndLog = (func) => {
  return (...args) => {
    var res = func.apply(undefined, args);
    console.log("Result is: " + res);
    return res;
  };
};
var squareAndLog = callAndLog(square);
squareAndLog(5); 

I know that arrow functions are loose, that's why i try here returning it within the parantheses ().

将箭头函数括在括号中对其行为没有影响。很少(如果有的话?)它会出现这种情况。

关于javascript - 为什么我不能返回箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43193796/

相关文章:

javascript - 将 bool 状态传递给多个 child

Javascript归约函数/三元运算符

javascript - 在/作为高阶函数中使用 jQuery 函数

javascript - 将事件处理程序附加到文档,没有文档标记,因此无法使用指令

javascript - 在 Javascript 中对 NaN 使用断言

javascript - 使用 react webpack 文件加载器提供静态 pdf

javascript - 在 JavaScript ES6 中,我如何只从散列中获取一些属性?

rust - 创建具有静态生存期的匿名变量时,最佳实践是什么?

Javascript 数组到 MySQL "In"值列表

javascript - CryptoJS 解密 C# DES 加密文件失败