[英]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:
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.在这个 function 中,
number
不应该是未定义的,因为我们只给出一个参数。 And that parameter gets multiplied and stored in number.. but anything that multiplies with undefined
is NaN
, right?并且该参数被乘以并存储在数字中..但是与
undefined
相乘的任何东西都是NaN
,对吗? Is the number = 1
here somehow? number = 1
在这里吗?
Since multiplier
function returning an arrow function with value of factor
, it is a different syntax for following simple definition.由于
multiplier
function 返回箭头 function ,其值为factor
,因此遵循简单定义的语法不同。
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
.在
console.log(twice(5))
中,您传递参数值 5,因此它将返回5 * 2
。
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(2);
multiplier returns a function,so twice is like this:乘数返回一个 function,所以两次是这样的:
twice = number => number * factor
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.