简体   繁体   中英

function example in text does not make sense to me

Reading through eloquent javascript in an attempt to wrap my head around functions, I read this example code:

function makeAddFunction(amount) {
  function add(number) {
    return number + amount;
  }
  return add;
}

var addTwo = makeAddFunction(2);
var addFive = makeAddFunction(5);
show(addTwo(1) + addFive(1));

I get the gist of it, but having examined the code and read the accompanying text several times over a few hours, this just hasn't clicked for me: What exacly is this code doing? Where does the add function acquire the number parameter? Does it come from the show command? If so, how does it get passed around? I just don't see it...

First off, I think there some code missing in your snippets because as it stands now, show would throw undefined.

But, there is enough here to answer the core of your questions.

1) var addTwo passes the value of 2 to makeAddFunction. This is "amount". addTwo gets returned an instance of add which has value of amount of 2.

2) var addFive passes the value of 5 to makeAddFunction. This is "amount". addFive gets returned an instance of add which has value of amount of 5.

3) addTwo is called with a number of 1. This is added to previous config value of 2 and returns 3.

4) addFive is called with a number of 5. This is added to previous config value of 5 and returns 6.

5) If a show function were defined, it would add 3+6 and show 9.

Where does the add function acquire the number parameter?

=> number is passed as an argument of add. When you write addTwo(1) , 1 will be the number parameter.

Where does the addTwo function acquire the amount parameter?

=> this is called a closure. When you run makeAddFunction(2) , the value 2 is passed as amount and gets captured by the add function.

The function makeAddFunction takes a number ( amount ) and returns a function that adds a number passed in as a paramter to the number passed into the outer function.

function makeAddFunction(amount) {
   function add(number) {
     return number + amount;
   }

    return add;
}

calling var addTwo = makeAddFunction(2); is equivalent to writing the following function:

   var addTwo = function(number) {
     return number + 2;  // this function is actually returned by makeAddFunction
   }

you can call it with a parameter addTwo(5);

Here's a fiddle: http://jsfiddle.net/Eh4LK/1/ press the run button to execute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM