Javascript 中的高阶函数 [英] Higher-order functions in Javascript
问题描述
我正在阅读 Eloquent JavaScript(新版本)并且我达到了高阶函数的一部分,我对以下代码中发生的事情感到困惑.
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.
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
为什么对函数的调用会有这样的噪音?(Boolean) 是演员表吗?演员表干什么?返回值?还是论点?为什么不是 (Boolean)noisy(0) 如果它的返回值.或者noise((Boolean) 0) 如果参数是被转换的那个.
Why is the call to the function noisy like this? Is (Boolean) a cast? A cast for what? the return value? or the argument? why not (Boolean)noisy(0) if its the return value. Or noisy((Boolean) 0) if the argument is the one being casted.
noisy(Boolean)(0)
这一行发生了什么?f() 在哪里定义?
What is happening in this line? Where is f() even defined?
var val = f(arg);
推荐答案
Boolean
是一个函数.这是您通过noisy
间接调用的函数.我知道这有点令人困惑,因为它看起来像一个类型的名称.但是在 JavaScript 中,那些最初被限制的东西(Boolean
、Number
、String
等等)是函数.当您调用Boolean
(without 使用new
)时,它会尝试将您提供的参数转换为boolean
原始值并返回结果.(请参阅规范中的 §15.6.1.)
Boolean
is a function. It's the function you're calling indirectly throughnoisy
. A bit confusing, I know, because it looks like the name of a type. But in JavaScript, those initially-capped things (Boolean
,Number
,String
, and so on) are functions. When you callBoolean
(without usingnew
), it tries to convert the argument you gave it into aboolean
primitive value and returns the result. (See §15.6.1 in the spec.)
f
是 noisy
函数中的参数名称.
f
is the name of the argument in the noisy
function.
JavaScript 中的函数是一流的对象.您可以将它们作为参数传递给其他函数,就像任何其他对象一样.
Functions in JavaScript are first-class objects. You can pass them into other functions as arguments just like any other object.
当你这样做
noisy(Boolean)(0)
有两件事正在发生.第一:
There are two things going on. First:
// (In effect, we're not really creating a variable...)
var x = noisy(Boolean);
这给了我们一个函数,当被调用时,它将使用我们给它的参数调用 Boolean
,同时执行那些 console.log
语句.这是您看到的在 noisy
(return function(arg)...
);
That gives us a function that, when called, will call Boolean
with the argument we give it while also doing those console.log
statements. This is the function you see being created in noisy
(return function(arg)...
);
然后我们调用该函数:
x(0);
那就是你看到控制台输出的时候.由于 Boolean(0)
是 false
,您会看到 Boolean
返回该值.
And that's when you see the console output. Since Boolean(0)
is false
, you see Boolean
return that value.
这是一个更简单的例子:
Here's a much simpler example:
function foo(bar) {
bar();
}
function testing() {
alert("testing got called");
}
foo(testing);
在那里,我将函数 testing
传递给 foo
.我在 foo
中使用的参数名称是 bar
.行 bar();
调用函数.
There, I'm passing the function testing
into foo
. The argument name I'm using for that within foo
is bar
. The line bar();
calls the function.
这篇关于Javascript 中的高阶函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!