What is closure?
It is my personal experience, I have never understood closure, I have read many articles & have seen many videos. Finally, I understood sometimes we even used a closure without realizing we were using a closure.First, understand the meaning of closure “an act or process of closing something”, now we can relate closure in javascript, closure is an inner function which wraps inside the outer function, which can access outer function scope & global function scope. for scoping you can read my previous blog:- http://uisource.blogspot.com/2018/08/javascript-variable-scoping.html
why do we create?
Global variables can be made local (private) with closures.To avoid the usage of global variables, use the local variables and wrap your code in the closure.
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain(Lexical scoping).
The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
A closure is a function having access to the parent scope, even after the parent function has closed.
Example
function outerFunc(){
var msg ="hello i am outer function variable"
function innerFunc(){
console.log(msg);
}
return innerFunc;
}
var y = outerFunc();
console.log(y) // output ƒ innerFunc(){ console.log(msg);}
y(); // hello i am outer function variable
The reference to the inner innerFunc(…) function that gets returned with
each call to the outer outerFunc(…) is able to remember whatever
msg
value inside outerFunc(…).
A closure is not only created when you return an inner function. In fact, the enclosing function does not need to return at all in order for its closure to be created.
Good job..
ReplyDelete