Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  71] [ 2]  / answers: 1 / hits: 30433  / 13 Years ago, fri, june 10, 2011, 12:00:00

Whats the main purpose of Closures in JS. Is it just used for public and private variables? or is there something else that I missed. I am trying to understand closure and really want to know what are the main advantages of using it.


More From » closures

 Answers
78

I think the best phrase to sum up the purpose of closures would be:


Data Encapsulation


With a function closure you can store data in a separate scope, and share it only where necessary.


If you wanted to emulate private static variables, you could define a class inside a function, and define the private static vars within the closure:


(function () {
var foo;
foo = 0;
function MyClass() {
foo += 1;
}
MyClass.prototype = {
howMany: function () {
return foo;
}
};
window.MyClass = MyClass;
}());

[#91765] Thursday, June 9, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathalieg

Total Points: 462
Total Questions: 106
Total Answers: 93

Location: Turks and Caicos Islands
Member since Tue, Mar 30, 2021
3 Years ago
;