Книга: Functional Programming in JavaScript
Назад: Working with functions
Дальше: Higher-order functions

Self-invoking functions and closures

What if we could return a function expression that in-turn returns the array? Variables declared in a function are available to any code within the function, including self-invoking functions.

By using a self-invoking function, our dilemma is solved.

var ValueAccumulator = function() {   var values = [];   var accumulate = function(obj) {     if (obj) {       values.push(obj.value);       return values;     }     else {       return values;     }   };   return accumulate; };  //This allows us to do this: var accumulator = ValueAccumulator(); accumulator(obj1);  accumulator(obj2);  console.log(accumulator());  // Output: [obj1.value, obj2.value]

It's all about variable scoping. The variable is available to the inner function, even when code outside the scope calls the functions. This is called a closure.

Note

Closures in JavaScript are functions that have access to the parent scope, even when the parent function has closed.

Closures are a feature of all functional languages. Traditional imperative languages do not allow them.

Назад: Working with functions
Дальше: Higher-order functions

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)