Please refer to How JavaScript Blocking Works? This may help you understand the closure.
Whenever you see the function keyword in another function, the inner function has access to the variables in the outer function.
function foo(x) { var tmp = 3; function bar(y) { alert(x + y + (++tmp)); } bar(10); } foo(2)
This will always warn 16, because bar can access x , which was defined as an argument to foo , and can also access tmp from foo .
it closing. A function must not be returned to be called a closure. Simply accessing variables outside your immediate vocabulary creates closure .
function foo(x) { var tmp = 3; return function (y) { alert(x + y + (++tmp)); } } var bar = foo(2);
The above function will also warn 16, because bar can still refer to x and tmp , even if it is no longer within the scope.
However, since tmp is still hanging inside the closing bar , it also increases. It will increase every time you call bar .
The simplest example of a closure is the following:
var a = 10; function test() { console.log(a);
When you call the Javascript function, a new execution context is created. Together with the function arguments and the parent object, this execution context also accepts all variables declared outside it (in the above example, both βaβ and βbβ).
You can create more than one closure function, either by returning a list of them, or by setting them to global variables. All of them will refer to the same x and the same tmp that they do not create their own copies.
[you]: Exciting, tell me more!
Here, the number x is a literal number. Like other JavaScript literals, when foo is called, the number x copied to foo as its argument is x .
JavaScript, on the other hand, always uses links when working with objects. If, say, you called foo with an object, the closure returned by it will refer to the original object!
function foo(x) { var tmp = 3; return function (y) { alert(x + y + tmp); x.memb = x.memb ? x.memb + 1 : 1; alert(x.memb); } } var age = new Number(2); var bar = foo(age);
As expected, each call to bar(10) will increment x.memb . You cannot expect x just refer to the same object as the age variable! After several calls to bar , age.memb will be 2! This link is the basis for memory leaks with HTML objects.