Using closures

To understand closure first we have to understand what is the scope, the scope is the set of variables you have access. It depends where and how you declare the variable. In Javascript you have a Local scope when you create a variable inside a function and you only have access to this variable inside this function or Global scope when the variable is created outside the function and it can be used on all the functions.

Closure are useful to encapsulate variables or functions, to get access to private functions, to manipulate a variable with local scope outside the function. It creates variables that can be accessed on the global scope even after the function where it was created has closed.


function closureFunc() {
var version = 2.3;
function getVersion() {
alert(version);
}
return getVersion;
}

var myFunc = closureFunc();
myFunc();
// Another example, using self-invoking function

var add = (function () {
var counter = 0;
return function () {return counter += 1;}
})();

add();
add();
add();

// the counter is now 3

 

 

 

Leave a comment

Create a website or blog at WordPress.com

Up ↑