为什么我不能 return 箭头函数?

Why can't I return an arrow function?

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

虽然这按预期工作:

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

这里,当我 return 一个箭头函数安装时,它不起作用:

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

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

来自 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 对象绑定到它们的主体。您的函数依赖于 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 ().

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

箭头函数没有 arguments 对象,您可以像这样使用 rest parameter syntax (...):

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