JavaScript closure explained

Closures are a way to let a function have persistent, private variables – that is, variables that only one function knows about, where it can keep track of info from previous times.It is an inner function that has access to outer function variables and parameters in addition to its own variables in its scope. In simple words, it is a function inside another function. These functions could be named functions or Anonymous.
Here is a sample closure:
Think about a scenario where we need to keep track of the mouse click happened in a session on a page:

<script type="text/javascript">
    var incrementClickCount = (function () {
        var clickCount = 0;
        return function () {
            return ++clickCount;
        }
    })()
</script>
<input type="button" value="Click Me" onclick="alert(incrementClickCount());" />
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s