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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function myFunction() { | |
name = "Deepak"; | |
function displayName() { | |
console.log(name); | |
} | |
show(displayName); | |
} | |
function show(displayName) { | |
displayName(); // "Deepak" | |
} | |
myFunction(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function myFunction() { | |
name = "Deepak"; | |
return function() { | |
console.log(name); | |
}; | |
} | |
function show() { | |
myFunction()(); // "Deepak" | |
} | |
show(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var add = (function() { | |
var count = 0; // private variable | |
return function() { // public anonymous function | |
count += 1; | |
console.log(count); | |
}; | |
})(); | |
add(); // 1 | |
add(); // 2 | |
add(); // 3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Link 2 - Closure
Link 3 - Closure
Link 4 - Closure
No comments:
Post a Comment