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
。
我不明白为什么第二个参数
(0)
包含在第二对括号中,而不是包含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
是一个函数,它在调用时返回另一个接受单个参数的函数。
所以,在下面的声明中
noisy(Boolean)(0);
Boolean
作为参数传递给 noisy
函数,0
传递给内部函数。
-
I don't understand why the second parameter
(0)
is contained in a second pair of brackets, & not withBoolean
?你可以,但为此需要改变一些事情。这使用了闭包的概念,其中内部函数可以访问外部函数的参数。
// 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)();
-
Why does val have to be returned?
这完全取决于你。如果您想从函数中获取某些值,可以返回该值并捕获/分配到其他变量中。
关于javascript - 为什么这个函数有第二个参数在单独的括号中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37860664/