Lexical closures
A closure is a function object that has access to variables in itslexical scope, even when the function is used outside of its originalscope.
Functions can close over variables defined in surrounding scopes. In thefollowing example, makeAdder()
captures the variable addBy
. Wherever thereturned function goes, it remembers addBy
.
/// Returns a function that adds [addBy] to the
/// function's argument.
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);
}