2

여기 좀 더 상위 정렬 함수가 있습니다.화살표 기능을 반환 할 수없는 이유는 무엇입니까?

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 

그 화살표 기능이 느슨 알고, 그 이유 나는 여기에서 그것을 흉막 안에 넣으려고한다 (). 그것들도 없이는 작동하지 않습니다. MDN에서

+3

'squareAndLog (5); // 결과는 NaN입니다. - 문제를 재현 할 수 없습니다. 이 코드를 실행하면 예외가 발생합니다. "ReferenceError : arguments is defined – Quentin

+2

Arrow 함수 [arguments를 바인딩하지 않습니다.] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/ 함수/Arrow_functions # No_binding_of_arguments), 두 번째 예제에서는 예상 한 것을 적용하지 않습니다. 대신에 ((... args) => ...를 사용하십시오. [this] (http://stackoverflow.com/ 질문/30935336/공식 정보 -에 - es6 - 화살표 기능에서) 및 [this] (http://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are -they-equivalent-exch) –

답변

3

화살표의 기능을 대신 사용할 수 있으며, arguments Object가없는 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);

9

는 :

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

나는 그것을 이해하지만, Quentin은 다르게 제안하는 것처럼 보인다. 어쩌면 일부 브라우저는 다르게 취급합니까? – Li357