为什么这个函数在单独的括号中有第二个参数?

时间:2016-06-16 13:25:42

标签: javascript higher-order-functions

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);

// calling with 0
// Called with 0 - got false

据我所知,更高的功能可以是改变其他功能的功能,如上例所示。我理解为什么第二个console.log会给出Called with 0 - got false作为它的输出。

  1. 我不明白为什么第二个参数(0)包含在第二对括号中,&不是Boolean

  2. 为什么必须返回val

1 个答案:

答案 0 :(得分:4)

让我们打破代码。

function noisy(f) {
    return function (arg) {
        console.log("Calling with", arg);
        var val = f(arg);
        console.log("Called with", arg, "- got", val);
        return val;
    };
}

var fn = noisy(Boolean); // fn now is the inner function
var value = fn(0);       // Calling the inner function

如代码所示,noisy是一个函数,它在调用时返回另一个接受单个参数的函数。

所以,在下面的陈述中

noisy(Boolean)(0);

Boolean作为参数传递给noisy函数,0传递给内部函数。

  1.   

    我不明白为什么第二个参数(0)包含在第二对括号中,&不是Boolean

    你可以,但为此,有些事情需要改变。这使用了闭包的概念,其中内部函数可以访问外部函数的参数。

    // Pass two arguments to `noisy()`
    function noisy(f, arg) {
        return function () {
    
            // Arguments can still be accessed here
            console.log("Calling with", arg);
            var val = f(arg);
            console.log("Called with", arg, "- got", val);
            return val;
        };
    }
    
    // To call, the second braces need to be used
    var val = noisy(Boolean, 0)();
    
  2.   

    为什么必须退回val?

    这完全取决于你。如果你想从函数中获取一些值,你可以返回值,并在其他变量中 catch / assign

相关问题