A closure is a technique which helps us to access the variable of other function even when they are out side the scope of the calling function. We can also say that it has access to the outer functions private variables.
Example : The private variable of any function can be accessed out side of the function with the help of Closure technique.
Scenario where you might use it
i) Access to its own scope
ii) Access to the outer functions variables and
iii) Access to the global variables
Closures can be particularly useful when dealing with callbacks.
Example:
function
makeList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
result.push(function () { alert(item + ' ' + list[i]) });
}
return result;
}
function showList() {
var list = makeList([1, 2, 3]);
for (var j = 0; j < list.length; j++) {
list[j]();
}
}
- makeList() function will be called 3
times by showList() function as
there are 3 array elements in
makeList() function parameter.
- Array variable result[] will be
populated with self invoked
functions and will be return to it's
calling function showList()
- Self invoking function will be
executed just once only.
- Now the returned value by makeList()
function will be assigned to
Variable list.
- Lastly, the loop will be executed 3
times and it will show the output in
form of alert message showing item
of list.
0 Comment(s)