Higher-order functions in Javascript

前端 未结 4 552
后悔当初
后悔当初 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条回答
  •  Happy的楠姐
    2020-11-27 05:52

    In case you're still having trouble with this, here's how I understand it (it gave me a headache too..)

    function noisy(f) {
        return function(arg) {
            console.log("calling with", arg);
            var val = f(arg);
            console.log("called with", arg, "- got", val);
            return val;
        };
    }
    
    noisy(Boolean)(0)
    

    A function is just a regular value. The previous sentence is key to understanding what's going on here.

    Our noisy(f) function is a value. It is what it returns.

    noisy(f) returns a function which takes an argument (arg).

    noisy(f) also takes an argument (f). Inner functions (functions called from within functions) have access to variables and arguments which were passed to the outer function.

    We're calling our outer function and passing it the argument Boolean. Our outer function returns its inner function which takes an argument (0). By understanding the above it should become clear that noisy(Boolean(0)) would simply pass an argument to our outer function, while not passing anything to the inner function which is returned by our outer function.

    It's so simple really. Now that we understand it, it's hard to believe it gave us such a headache to begin with... */`

提交回复
热议问题