场景
1. 异步(Async)
for(var i=0;i<5;i++){
setTimeout(function(){
console.log(i);
},100);
}
输出:
5
5
5
5
5
闭包写法
for(var i=0;i<4;i++){
setTimeout((function(i){
console.log(i);
})(i),100);
}
或
for(var i=0;i<5;i++){
setTimeout(fun(i),100);
}
function fun(i){
console.log(i);
}
输出:
0
1
2
3
4
2. 避免命名空间污染 (namespace)
lib/a.js
var i = 111;
alert(i);
function a() {
alert('Hello');
}
lib/b.js
var i = 222;
alert(i);
function a() {
alert(i);
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="lib/a.js"></script>
<script src="lib/b.js"></script>
</head>
<body>
<button οnclick="a()">a</button>
<button οnclick="b()">b</button>
</body>
</html>
运行index.html
输出
1. 111
2. 222
点击a按钮,输出222.
点击a按钮,输出222.
闭包写法
lib/a.js
function a() {
var i = 111;
function fun1() { alert(i); }
return {
fun1: fun1
};
}
a = a();
lib/b.js
function b() {
var i = 222;
return function() { alert(i); };
}
var b = b();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="lib/a.js"></script>
<script src="lib/b.js"></script>
</head>
<body>
<button οnclick="a.fun1()">a</button>
<button οnclick="b()">b</button>
</body>
</html>
运行index.html
点击a按钮,输出111.
点击a按钮,输出222.
1. 对于闭包中使用的的外部变量, 通过Scope chain 往上找,找到为止(scope chain just for function & static)
2. 注意this,this依赖运行上下文(dynamic)
Source code
git:https://github.com/tianxia1221/Sample.git (folder: javascript_closure)