为什么我不能返回箭头功能?
问题描述:
我在这里有一个更高级的sorta函数。为什么我不能返回箭头功能?
虽然这按预期工作:
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
这这里,当我返回箭头功能insted的,不工作:
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
我知道箭头功能松动,这就是为什么我尝试在这里将它归回()
。没有他们也不行。
答
箭功能,不具备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);
答
从MDN:
An arrow function expression has a shorter syntax than a function expression and does not bind its own
this
,arguments
,super
, ornew.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().
内附您的箭头功能括号中对自己的行为没有任何影响。几乎没有(如果有的话)情况。
'squareAndLog(5); //结果是NaN' - 我无法重现问题。当我运行该代码时,它会抛出一个异常:“ReferenceError:参数未定义 – Quentin
箭头函数[不绑定参数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/函数/ Arrow_functions#No_binding_of_arguments),所以在你的第二个例子中,你并没有应用你所期望的,使用'(... args)=> ...'来代替,参见[this](http://stackoverflow.com/问题/ 30935336 /官方信息的参数中的es6箭头功能)和[这](http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are -they-equivalent-exch) –