The following points define the importance or need of JavaScript Closure.
=> Use For Callbacks and Events
This is where, Closure plays a vital role. Basically, this is the reason, why closure is so popular.
Closure helps to get sequential results from any function. Closure basically approach Lexical scope to get the result. The simple example is 'setTimeout'.
Below example will clear it in a best way.
function getMessageFunction(message, timeout) {
// Define handle in the closure
function handle() {
console.log(message);
}
setTimeout(handle, timeout);
}
//function values
getMessageFunction("Wake UP!", 100);
=> Use For Object Oriented(OO) Javascript
A very interesting fact related with closure is that it is a better way to implement an object-oriented program. The main reason for this, Closure is the simple and convenient approach to give a function access to the local object. Many Study shows that Closure is the best approach to implement data structures without the need to built-in a complex data types.
A Simple Example -
function counterValue() {
var val = 0;
function getValue() {
return val;
}
function incValue() {
val += 1;
}
return [getValue, incValue];
}
function get_countValue(counterValue) {
return counterValue[0]();
}
function inc_countValue(counterValue) {
counterValue[1]();
}
var counterValue = counterValue();
inc_countValue(counterVal );
inc_countValue(counterVal );
console.log(get_countValue(counterVal));
=> To Emulate Static Variables
Just like Visual Basics, there are lots of similarities between VB(Visual Basic) language Static variables and the variables within the Closure.
Basically static variables are really useful because they provide or offer the security of presence of local variables while maintaining backbone of global ones.
Closures are used to act like static variables because any modification in the enclosed variables to retained the values between calls.
0 Comment(s)