JS: Closure
JavaScript supports Closure .
often, closure is used for a function to maintain a local state.
const ff = () => { let dog = 0; return (() => { dog = dog + 1; return dog; }); }; const hh = ff(); // hh is now a closure // hh maintains a state console.assert(hh() === 1); console.assert(hh() === 2); console.assert(hh() === 3); /* In this example, the function ff() returns the function gg. ff() sets up a variable dog, and the inner function gg uses it. When ff() is called, gg is returned. gg is no longer in the context of ff, but the function gg still has the variable it uses. */
Closure with shared variable context
More than one function can share the same variable context.
// example of closure functions sharing context function ff() { let dog = 0; return { "f": function () { dog = dog + 1; return dog; }, "g": function () { dog = dog - 1; return dog; }, }; } const xobj = ff(); console.assert(xobj.f() === 1); console.assert(xobj.f() === 2); console.assert(xobj.f() === 3); console.assert(xobj.g() === 2); console.assert(xobj.g() === 1); console.assert(xobj.g() === 0); /* Here, the function ff returns a object, and the object has 2 properties, each's value is a function. */