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();
I’ve used closures to do things like:
As you can see there,
ais now an object, with a methodpublicfunction(a.publicfunction()) which callsprivatefunction, which only exists inside the closure. You can not callprivatefunctiondirectly (i.e.a.privatefunction()), justpublicfunction().It’s a minimal example, but maybe you can see uses to it? We used this to enforce public/private methods.