Js 闭包
1 Lexical Scope(词法范围)
In JavaScript, functions have lexical scope. This means that functions create their
environment (scope) when they are defined, not when they are executed.
>>> function f1(){var a = 1; f2();}
>>> function f2(){return a;}
>>> f1();
a is not defined
Inside the function f1() we call the function f2(). Because the local variable a is also
inside f1(), one might expect that f2() will have access to a, but that's not the case. At
the time when f2() was defined (as opposed to executed), there was no a in sight. f2(),
just like f1(), only has access to its own scope and the global scope. f1() and f2() don't
share their local scopes.
2 Closures in a Loop
function f() {
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = function(){
return i;
}
}
return a;
}
>>> var a = f();
>>> a[0]()
3
>>> a[1]()
3
>>> a[2]()
3
What happened here? We created three closures that all point to the same local variable i.
Closures don't remember the value, they only link (reference) the i variable and will
return its current value. After the loop, i's value is 3. So all the three functions point
to the same value.
function f() {
var a = [];
var i;
for(i = 0; i < 3; i++) {
a[i] = (function(x){
return function(){
return x;
}
})(i);
}
return a;
}
>>> var a = f();
>>> a[0]();
0
>>> a[1]();
1
>>> a[2]();
2
He
javascript闭包 来自淘豆网m.daumloan.com转载请标明出处.