Sunday, December 21, 2014

Closure in JavaScript

Closure is when a function remembers its lexical scope even when the function is executed outside its lexical scope.
We can make private variable with closure.

For Example

function myFunction() {
name = "Deepak";
function displayName() {
console.log(name);
}
show(displayName);
}
function show(displayName) {
displayName(); // "Deepak"
}
myFunction();
view raw gistfile1.js hosted with ❤ by GitHub
function myFunction() {
name = "Deepak";
return function() {
console.log(name);
};
}
function show() {
myFunction()(); // "Deepak"
}
show();
view raw gistfile1.js hosted with ❤ by GitHub
var add = (function() {
var count = 0; // private variable
return function() { // public anonymous function
count += 1;
console.log(count);
};
})();
add(); // 1
add(); // 2
add(); // 3
view raw gistfile1.js hosted with ❤ by GitHub
var name = (function() {
var name = "Deepak"; // private variable
return { // public API
getName: function() {
return name;
},
setName: function(newName) {
name = newName;
}
};
})();
console.log(name.getName()); // "Deepak"
name.setName("Chetan");
console.log(name.getName()); // "Chetan"
view raw gistfile1.js hosted with ❤ by GitHub
Link 1 - Closure
Link 2 - Closure
Link 3 - Closure
Link 4 - Closure

No comments:

Post a Comment