开发者

Makeadder example from Ben Alman

开发者 https://www.devze.com 2023-02-05 07:00 出处:网络
In the below, where does b come from? I don\'t see it being passed in, so how could it be returned? function lockInFir开发者_StackOverflow中文版stArg( fn, a ) {

In the below, where does b come from? I don't see it being passed in, so how could it be returned?

function lockInFir开发者_StackOverflow中文版stArg( fn, a ) {
  return function( b ) {
    return fn( a, b );
  };
}

Link: http://msdn.microsoft.com/en-us/scriptjunkie/gg575560

More complete excerpt:

// More-general functions.
 
function add( a, b ) {
  return a + b;
}
 
function multiply( a, b ) {
  return a * b;
}
 
// Relatively flexible more-specific function generator.
 
function lockInFirstArg( fn, a ) {
  return function( b ) {
    return fn( a, b );
  };
}
 
var add1 = lockInFirstArg( add, 1 );
add1( 2 );    // 3
add1( 3 );    // 4
add1( 10 );   // 11


templatetypedef has already provided an explanation, I'll show you little breakdown in code.

Our setup:

function add( a, b ) {
  return a + b;
}

function lockInFirstArg( fn, a ) {
  return function( b ) {
    return fn( a, b );
  };
}

Now let's look at the following:

var add1 = lockInFirstArg( add, 1 );

And break it down:

// passes in the function object and 1 as arguments
var add1 = lockInFirstArg(function add( a, b ) {
  return a + b;
}, 1 );

// the lockin function will look a bit like this
function lockInFirstArg( fn, a ) {
  // fn = function add
  // a = 1

  // returns a new function which calls fn aka add
  // this function is also a closure, that means it keeps access to the scope of
  // lockInFirstArg so it can still use the variable a, even after it was returned
  return function( b ) {
    return a + b; // inlined add
  };
}

So in the end he var add1 = assigment is equal to:

//  is equal to this
var add1 = function( b ) {
    return 1 + b;
};

What comes into play here is that functions are both first class objects and closures, no magic just plain JavaScript :)


The point of this code is that b is the parameter of a new function produced by calling lockInFirstArg. The intuition is that you call lockInFirstArg passing in a function fn which takes two arguments and some other value a. It then produces a function which, if given some value (let's call it b), applies the function fn to a and b. This is similar to taking the function fn, locking the parameter a in place, then returning the resulting function.

By the way, this term is sometimes called "currying." This has a technical meaning, but it's pretty close to the meaning of this code here.

0

精彩评论

暂无评论...
验证码 换一张
取 消