下载此文档

javascript闭包.pdf


文档分类:IT计算机 | 页数:约2页 举报非法文档有奖
1/2
下载提示
  • 1.该资料是网友上传的,本站提供全文预览,预览什么样,下载就什么样。
  • 2.下载该文档所得收入归上传者、原创者。
  • 3.下载的文档,不会出现我们的网址水印。
1/2 下载此文档
文档列表 文档介绍
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转载请标明出处.

相关文档 更多>>
非法内容举报中心
文档信息
  • 页数2
  • 收藏数0 收藏
  • 顶次数0
  • 上传人bjy0415
  • 文件大小0 KB
  • 时间2015-05-10
最近更新