理解
- 关于闭包
function fun(n, o) {
console.log(o);
return {
fun: function (m) {
return fun(m, n);
}
}
}
var a = fun(0);
a.fun(1);
a.fun(2);
a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3);
var c = fun(0).fun(1);
c.fun(2);
c.fun(3);
答案:
undefined
0
0
0
undefined
0
1
2
undefined
0
1
1
用arguments.callee和闭包实现的函数封装
var data = [];
for (var i = 0; i < 3; i++) {
(data[i] = function () {
console.log(arguments.callee.i);//此处i不是外部i
}).i = i;
}
data[0](); //0
data[1](); //1
data[2](); //2
应用
- 利用闭包实现自动递增计数
var countNumber = (function() {
var num = 0;
return function() {
return ++num;
}
})();
console.log(countNumber());//1
console.log(countNumber());//2
console.log(countNumber());//3
console.log(countNumber());//4