In example below there (num i) stuff, where it get it's value when makeAddr() called ?
Function makeAdder(num addBy) {
return (num i) => addBy + i;
}
void main() {
// Create a function that adds 2.
var add2 = makeAdder(2);
// Create a function that adds 4.
var add4 = makeAdder(4);
assert(add2(3) == 5);
assert(add4(3) == 7);
}
The
makeAdderfunction returns function. The function it returns is created by evaluating the function expression(num i) => addBy + i. When you evaluate a function expression you create a function value. The function value is also called a closure because it contains ("closes over") all the "free" variables in the function body - those that are not declared by the function expression itselfIn this case the function expression
(num i) => addBy + icontains the free variableaddBy. The function value/closure knows what that variable means - it's the parameter of the call tomakeAdderthat the function expression is evaluated in. Every call tomakeAddercreates a newaddByvariable, and every call also creates a new closure closing over that new variable.The closure is not just storing the value of the variable, it's referencing the variable itself. You can see that if your closure changes the value of variable.
Example: