Resource: You Don’t Know JS
Closure
one of the most important, powerful, useful and least understood techniques in JS
- “a way to ‘remember’ and continue to access a function’s scope (its variables) even once the function has finished running”
Example:
function makeAdder(x) { //parameter 'x' is an inner variable // inner function 'add()' uses 'x', so // it has a "closure" over it function add(y) { return y + x; }; return add; }
- with each call to the outer makeAdder (..) function, the reference to the inner add(..) function gets returned
- and add(..) remembers the x value that was passed in to makeAdder(..)
// 'plusOne' gets a reference to the inner 'add(..)' //function with closure over the 'x' parameter of // the outer 'makeAdder(..); var plusOne = makeAdder(1); //'plusTen' gets a reference to the inner 'add(..)' // function with closure over the 'x' parameter of // the outer 'makeAdder(..); var plusTen = makeAdder(10); plusOne(3); //4 <-- 1 + 3 plusOne(41); // 42 <-- 1 + 41 plusTen(13); // 23 <-- 10 + 13
How this code works:
- call makeAdder(1), get back a reference to its inner add(..) that remembers x as 1 ; name{?} this function reference plusOne(..)
- call makeAdder(10), get back another reference to its inner add(..) that remembers x as 10; name{?} this function reference plusTen(..)
- call plusOne(3), it adds 3 (its inner y) to the 1 (remembered by x); get 4 as the result
- call plusTen(13), it adds 13 (its inner y) to the 10 (remembered by x); get 23 as the result
QUESTIONS:
- Is plusTen both a variable name and a function (or function reference)?
- What is the difference between function and function reference?