JavaScript
Closure: A closure is the combination of a function (inner
function) which have access to the parent scope (outside function variable).
Advantages of closure:
1)
In the object-oriented programming paradigm,
encapsulation is one of the key features. Encapsulation hides the inner work of
an object from the outside world. But as JavaScript is a scripting language it
doesn’t have encapsulation feature.
Here Closure comes in a
picture, with the help of “Closure” we can access the parent function variable
and arguments.
2)
Example:
var myFun = (function () {
var privateFun
= function () {
alert('
privateFun ');
}
return {
publicFun
: function () {
privateFun();
}
}
})();
In this example, I can access
the publicFun but not privateFun.
3)
Closures are helpful in APIs callback functions
requirement.
There are many examples
available for closure, if you want to explore more.