JS: Closure
Closure is a feature of computer languages. It is a way for function to maintain state, in a clean way. Practically speaking, the effect is the same as setting global variable inside function, but the variables are hidden and private.
Here's a example of closure in JavaScript.
// closure example function myContext() { let x = 0; function f() { x += 1; return x; }; return f; }; const g = myContext(); // g is now function with closure // g maintains a state console.log(g()); // 1 console.log(g()); // 2 console.log(g()); // 3
In this example, the function myContext() returns the function f.
myContext() sets up a variable x, and the inner function f uses it. When myContext() is called, f is returned. The function f still has its scope context.
How to create a closure:
- Define a function c.
- Declare some variables in c.
- Define a inner function f that use these variables.
- Return f in c.
- Now, the outter function c and assign it to a variable like this:
const g = c();. - This variable g is a function with closure.
Closure with Shared Variable Context
More than one function can share the same variable context.
// example of closure functions sharing context function myContext() { let x = 0; return { "f": function () { x++; return x; }, "g": function () { x--; return x; }, }; }; const c = myContext(); console.log(c.f()); // 1 console.log(c.f()); // 2 console.log(c.f()); // 3 console.log(c.g()); // 2 console.log(c.g()); // 1 console.log(c.g()); // 0
Here, the function myContext returns a object, and the object has 2 properties, each's value is a function.
Function with State, Using Properties
JavaScript function is a object [see JS: Object Type], so it has properties, and we can use the properties to maintain state.
// function with state, using properties function f () { f.x += 1; return f.x; }; f.x = 0; // x is a property, used as state console.log(f()); // 1 console.log(f()); // 2 console.log(f()); // 3
This is simpler than closure but achieve the same effect.
The disadvantage is that the variables (the properties) are not private. Anyone can see them.
Function Topic
- JS: Define Function
- JS: Functional Programing
- JS: Arrow Function
- JS: Function Parameters
- JS: f Declaration vs Expression
- JS: Closure
- JS: Function Call, Apply, Bind
- JS: Function Argument Default Value
- JS: Function Rest Parameters
- JS: Function Argument Destructure
- JS: Function Object
- JS: Function.prototype
If you have a question, put $5 at patreon and message me.