-3

Can someone point to a simple example to understand closure in detail?

the below link http://www.kirupa.com/html5/closures_in_javascript.htm is not clear.

Thanks.

Kathir
  • 23
  • 1
  • 5

3 Answers3

0

A closure is a function that uses references from higher-level scopes.

For example:

// Sorrounding scope
var a = "hello world";

var func = function() {
    // Function scope
    var b = a + " !!!!";
};

See Closure (computer programming) on Wikipedia to learn more about what's a closure in depth.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

Consider the following

var noun = 'Governor';

var foo = (function () {
    var bar = 'Hello';
    // A
    return function () {
        var baz = 'Blake';
        console.log(bar, noun, baz);
        // B
    };
}());
// C
foo();
  • At line A, which identifiers are referencable? noun, foo, bar
  • At line B, which identifiers are referencable? noun, foo, bar, baz
  • At line C, which identifiers are referencable? noun, foo

Now go on to think, if only noun, foo are referenceable at line C, why are the values of bar and baz appearing when we foo()? More specifically, why is bar still there? It isn't even defined in the function we've assigned as foo.

// remember, `foo` looks like this (log it to check for yourself)
function () {
    var baz = 'Blake';
    console.log(bar, noun, baz); // `bar` used but _not defined here_
    // B
}

This is because foo is a closure. There are identifiers "wrapped up" inside it which continue to live on for as long as foo lives.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

Here is a function that defines the variable number, then defines a function that references that variable. The inner function keeps a reference to number even when the outer function has closed off. The variable is basically in a pocket universe now where only the inner function can see it.

(function(){
    var number = 0;
    window.count = function(){
        number = number + 1;
        console.log(number);
    };
})()

count();
// 1

count();
// 2

console.log(number);
// number is not defined
autodidact
  • 256
  • 1
  • 6