为什么我不能返回箭头功能?

问题描述:

我在这里有一个更高级的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 

我知道箭头功能松动,这就是为什么我尝试在这里将它归回()。没有他们也不行。

+3

'squareAndLog(5); //结果是NaN' - 我无法重现问题。当我运行该代码时,它会抛出一个异常:“ReferenceError:参数未定义 – Quentin

+2

箭头函数[不绑定参数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/函数/ Arrow_functions#No_binding_of_arguments),所以在你的第二个例子中,你并没有应用你所期望的,使用'(... args)=> ...'来代替,参见[this](http://*.com/问题/ 30935336 /官方信息的参数中的es6箭头功能)和[这](http://*.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are -they-equivalent-exch) –

箭功能,不具备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 , 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().

内附您的箭头功能括号中对自己的行为没有任何影响。几乎没有(如果有的话)情况。

+0

但是它不应该给出一个'ReferenceError'?或者它在某种程度上依赖于浏览器? – Li357

+0

@AndrewLi如果OP的代码包含在一些其他非箭头函数中, 'arguments'将引用来自外部函数被调用的'arguments'对象。 – JLRishe

+0

我明白,但昆丁似乎有不同的建议。也许有些浏览器对待它的方式不同? – Li357