为什么此函数在单独的括号中有第二个参数? [英] Why does this function have a second parameter in separate brackets?

查看:126
本文介绍了为什么此函数在单独的括号中有第二个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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作为其输出.

I understand that higher function can be functions that change other functions, like the example above. I understand why the second console.log gives Called with 0 - got false as it's output.

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

  1. I don't understand why the second parameter (0) is contained in a second pair of brackets, & not with Boolean?

为什么必须返回val?

推荐答案

让我们打破代码.

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是一个函数,在调用时将返回另一个接受单个参数的函数.

As seen in the code, noisy is a function which returns another function when invoked which accepts a single parameter.

所以,在下面的语句中

noisy(Boolean)(0);

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

Boolean is passed as parameter to the noisy function and 0 is passed to the inner function.

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

I don't understand why the second parameter (0) is contained in a second pair of brackets, & not with Boolean?

您可以,但是为此需要进行一些更改.它使用闭包的概念,其中内部函数可以访问外部函数的参数.

you can, but for that some things need to be changed. This uses the concept of closure where the inner function has the access to the parameters of the outer function.

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

  • 为什么必须返回val?

    Why does val have to be returned?

    这完全取决于您.如果要从函数中获取一些值,则可以返回该值,并在其他变量中 catch/assign .

    That's totally upto you. If you want to get some value from the function, you can return the value and catch/assign it in other variable.

    这篇关于为什么此函数在单独的括号中有第二个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆