What is a practical use for a closure in JavaScript?

Posted by alex on Stack Overflow See other posts from Stack Overflow or by alex
Published on 2010-04-28T09:39:19Z Indexed on 2010/04/28 9:43 UTC
Read the original article Hit count: 232

Filed under:
|

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

I get that by returning an inner function, it will have access to any variable defined in it's 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();

Thanks

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures