2014-09-30 4 views
1

현재 제 5 장 Eloquent Javascript를 읽고 있습니다. 다음 예제는 나 혼란을 일으키는 다음 예제를 제공합니다.자바에서 고차 함수 이해하기

function greaterThan(n) { 
    return function(m) { return m > n; }; 
} 
var greaterThan10 = greaterThan(10); 
console.log(greaterThan10(11)); 
// → true 

누구나 가능한 한 간단하게이 문제를 해결할 수 있습니까? 나는 콜백에 큰 문제가있다. 특히 이러한 상황에 관해서.

답변

7

고차원 적 기능은 기본적으로 두 가지를 의미한다 :

이 무엇을 의미하는지입니다

  • 기능 할 수 반환 기능 인수/입력으로 다른 기능을 할 수
  • 기능 고차 함수.

    // this function takes a function as an argument 
    function myFunc(anotherFunc) { 
        // executes and returns its result as the output which happens to be a function (myFunc) 
        return anotherFunc(); 
    } 
    
    // let's call myFunc with an anonymous function 
    myFunc(function() { 
    // this returns a function as you see 
    return myFunc; 
    }); 
    

    예를 들어, 함수를 반환하여 상위 함수를 보여줍니다. 또한 종결의 개념을 보여줍니다.

    범위 지정 변수 (이 경우 입력 인수 n)를 통해 클로저가 닫힙니다.

    function greaterThan(n) { 
        // n is closed over (embedded into and accessible within) the function returned below 
        return function(m) { return m > n; }; 
    } 
    
    // greatherThan10 reference points to the function returned by the greaterThan function 
    // with n set to 10 
    // Notice how greaterThan10 can reference the n variable and no-one else can 
    // this is a closure 
    var greaterThan10 = greaterThan(10); 
    
    console.log(greaterThan10(11)); 
    // → true 
    
  • 6

    여기에 관련된 "콜백"이 없습니다. "greaterThan"함수로 얻은 것은 다른 함수를 반환하는 함수입니다. 이제 변수 "greaterThan10는"인수로 10 호출은 "초과]"함수에 의해 반환 된 함수를 참조

    var greaterThan10 = greaterThan(10); 
    

    :

    그래서, 당신은 함수를 호출합니다. 호출

    console.log(greaterThan10(11)); 
    

    기능은 "초과]"에서 반환

    그런 다음 해당 함수를 호출 한 결과를 기록합니다. 이 매개 변수는 생성 될 때 전달 된 매개 변수 "n"의 값과 해당 매개 변수를 비교합니다. 11이 실제로 10보다 크기 때문에이 함수는 true을 반환하며 그 값은 기록됩니다.