Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  180] [ 5]  / answers: 1 / hits: 142722  / 14 Years ago, wed, april 28, 2010, 12:00:00

I'm trying my hardest to wrap my head around JavaScript closures.



I get that by returning an inner function, it will have access to any variable defined in its immediate parent.



Where would this be useful to me? Perhaps I haven't quite got my head around it yet. Most of the examples I have seen online don't provide any real world code, just vague examples.



Can someone show me a real world use of a closure?



Is this one, for example?



var warnUser = function (msg) {
var calledCount = 0;
return function() {
calledCount++;
alert(msg + 'nYou have been warned ' + calledCount + ' times.');
};
};

var warnForTamper = warnUser('You can not tamper with our HTML.');
warnForTamper();
warnForTamper();

More From » closures

 Answers
17

I've used closures to do things like:


a = (function () {
var privatefunction = function () {
alert('hello');
}

return {
publicfunction : function () {
privatefunction();
}
}
})();

As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction, which only exists inside the closure. You can not call privatefunction directly (i.e. a.privatefunction() ), just publicfunction().


It's a minimal example, but maybe you can see uses to it? We used this to enforce public/private methods.


[#96941] Monday, April 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destiniemartinac

Total Points: 92
Total Questions: 106
Total Answers: 111

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;