简体   繁体   中英

How does a closure work when there's only one parameter but two variables in it?

Here's the function that I'm talking about:

function multiplier(factor) {
    return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));

// output → 10

In this function shouldn't number be undefined since we're only giving one parameter. And that parameter gets multiplied and stored in number.. but anything that multiplies with undefined is NaN , right? Is the number = 1 here somehow?

Since multiplier function returning an arrow function with value of factor , it is a different syntax for following simple definition.

function twice(number) {
   // Value 2 is part of function definition as returned from multiplier() function
   return number * 2;
}

In console.log(twice(5)) you are passing parameter value 5, so it will return 5 * 2 .

function multiplier(factor) {
    return number => number * factor;
}
let twice = multiplier(2);

multiplier returns a function,so twice is like this:

twice = number => number * factor

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