Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
78 views
in Technique[技术] by (71.8m points)

Higher-order functions in 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
  1. 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)
    
  2. What is happening in this line? Where is f() even defined?

    var val = f(arg);
    
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Boolean is a function. It's the function you're calling indirectly through noisy. 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 call Boolean (without using new), it tries to convert the argument you gave it into a boolean primitive value and returns the result. (See §15.6.1 in the spec.)

  2. f is the name of the argument in the noisy function.

Functions in JavaScript are first-class objects. You can pass them into other functions as arguments just like any other object.

When you do

noisy(Boolean)(0)

There are two things going on. First:

// (In effect, we're not really creating a variable...)
var x = noisy(Boolean);

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

Then we call that function:

x(0);

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...