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.
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.
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.
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();
noun
, foo
, bar
noun
, foo
, bar
, baz
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.
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