A closure is a function having access to the parent scope, even after the parent function has closed. — w3schools
Understanding Function Scope
Every function can access the variables declared in the chain of parent lexical environments.
So, the child functions have access to the parent functions scope. why do we need a term Closures when the term functional scope is descriptive enough? Closures is a behavior exhibited when we deal with the functional scope. Let's see what happens during the last 4 lines.
const f1 = func1()
const f11 = f1.func11()
const f112 = f11.func112()
1. func1 gets added to the execution stack on top of the base Global execution context.
2. func1 Allocates b=2 in the memory space.
“A closure is a function having access to the parent scope, even after the parent function has closed”
The “even after ”is the key to understand closures.
Closures In The Valley Of Peace
Even after Master Oogway passed on to the heavens in a stream of peach blossoms, Even after Master Shifu got dismantled by Tai Lung, Po made use of the Closures to access the Dragon scroll (and dumplings) kept safe by Oogway and defeated Tai Lung.
Run the below script here
The Scope Chain And The Execution Stack Of The Characters
The function scope chain allows Po, Tai Lung and the uncredited cook to access and modify the states stored in Oogway context.
The scope chain flows downwards till the Global execution context.
Po's Closure is pretty much the same for Tai Lung and The uncredited cook.
Resources Oogway had long saved.S: Dragon Scrol
D: Dignity of the valley
— The End —