All variables inside the function body can be stored in the function scope. ----- Closures (function variables can be hidden inside the scope chain, so it looks like the function "wraps" the variable around)
When a function nests another function, the outer function returns the nested object as a return value. Often times closed. Understanding closures starts with understanding the lexical scoping rules for nested functions.
var scope = 'global scope'; function checkscope(){ var scope = 'local scope'; function f(){return scope}; return f; } checkscope()() //"local scope"
Feature: Local variables (and parameters) can be captured and persisted as if they were bound to the external function in which they were defined.
var unique = (function(){ var conter = 0; return function(){return conter++} }()); unique()
Use closures to implement private property accessor methods (a common practice for private state sharing):
function addPrivateProperty(o,name,predicate){ var value; o[`get${name}`] = function(){return value;}; o[`set${name}`] = function(v){ if(predicate && !predicate(v)) throw Error(`set ${name}:invalid value ${v}`) else value = v; } } var o = {}; addPrivateProperty(o,'Name',function(x){return typeof x == "string"}); o.setName("Frank"); console.log(o.getName());
Defining two closures in the same scope chain that share the same private variables or variables is a very important technique.
Important: The parameter array of the outer function cannot be directly accessed from within the closure, unless the outer function stores the parameter array in another variable:
var outerArguments = arguments ;
var that = this;