Closure Scope Chain
A closure is
the combination of an enclosed structure with references to its surrounding
state.A closure from an inner
function gives us access to the domain of an external function. Closures are
generated in JavaScript any time a function is created, at the time of creation
of the feature.
We
have three scopes for each closure:
- Local Scope (Own
scope)
- Outer Functions
Scope
- Global Scope
A
common mistake is not to understand that in the case where the outer function
is itself a nested function, access to the scope of the outer function requires
the outer function enclosing domain, effectively creating a chain of function
scopes.
EXAMPLE
//
global scope
let
a = 10;
function
sum(x){
return
function(y){
return
function(z){
//
outer functions scope
return
function(k){
//
local scope
return
x + y + z + k + a;
}
}
}
}
console.log(sum(1)(2)(3)(4));
// log 20
//
We can also write without anonymous functions:
//
global scope
let
a = 10;
function
sum(x){
return
function sum2(y){
return
function sum3(z){
//
outer functions scope
return
function sum4(k){
//
local scope
return
x + y + z + k + b;
}
}
}
}
var
s = sum(1);
var
s1 = s(2);
var
s2 = s1(3);
var
s3 = s2(4);
console.log(s3)
//log 20
In
the above example, we have a series of nested functions all having access to
the scope of the outer functions. We may claim in this sense that closures have
access to all the outer function scopes within which they have been defined.
Comments
Post a Comment