Higher-order functions in Javascript

前端 未结 4 550
后悔当初
后悔当初 2020-11-27 05:09

I am reading Eloquent JavaScript (The new edition) and I reached the part on higher order functions and I\'m confused on what\'s happening in the following code.

         


        
4条回答
  •  温柔的废话
    2020-11-27 05:55

    I'm relatively new to JS and I've also just been reading through Eloquent Javascript and I found it easier to understand once I understood the calling of the function (answering your point 1):

    noisy(Boolean)(0);
    

    The noisy(Boolean) creates a new function and the (0) is after it because it is being passed as an argument into that new function. If you refer back to the greater than example:

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

    It could also be called in this way:

    greaterThan(10)(11);
    

    I hope that clarifies your first question about why it was called that way.

    For the second question. The f in:

    var val = f(arg);
    

    is the Boolean function that was passed into noisy when noisy(Boolean) was entered. It was then used as the argument in the noisy function. I also didn't realise that Boolean could be a function in itself and not just a data type. As others have said - it converts the argument you gave it into a Boolean value and returns the result.

    Therefore val becomes Boolean(arg) which becomes Boolean(0) which evaluates to false. If you try call noisy(Boolean)(1);you will see it return true. The console.log("called with", arg, "- got", val); simply logs the argument (0 in this case) and the result of evaluating it (false).

    In effect, it has changed the Boolean function into one that logs the argument and result, as well as returning the result.

    I hope this helps. Just writing it has helped my own understanding.

提交回复
热议问题