简体   繁体   中英

What is the initial value of an argument in a function within a function?

Using the code below:

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

 var addTwo = makeAddFunction(2);
 var addFive = makeAddFunction(5);
 console.log(addTwo(1) + addFive(1));

The console prints out 9. I am assuming 'number' in the add function is zero but why is the value of 'number' initially 0?

There's no "initially 0" about this.

You're first returning a function that adds 2 to a number, then making a function that adds 5 to a number.

thus, you've effectively written:

console.log((2 + 1) + (5 + 1));

and 3 + 6 is 9.

addTwo is essentially:

var addTwo = function (number) {
     return number + 2;
 }

add addFive is:

var addFive = function (number) {
     return number + 5;
 }

because you're using this as a closure .

When you call makeAddFunction , it takes the parameter you passed in for amount and then returns that inner function.

Thus when you pass in 2, it returns this:

 function add(number) {
     return number + 2;
 }

Then you are setting that code to the addTwo variable. So when you call addTwo with a parameter of 1, it returns 1+2 (3)

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