//闭包引起的bug
function bug() {
var nums = [];
for (var i = 0; i < 3; i++) {
nums[i] = function () {
return i;
};
}
return nums;
}
var nums_bug = bug();
console.log(nums_bug[0]());
console.log(nums_bug[1]());
console.log(nums_bug[2]());
//修复bug
function fbug() {
var nums = [];
for (var i = 0; i < 3; i++) {
nums[i] = (function (i) {
return i;
})(i);
}
return nums;
}
var nums = fbug();
console.log(nums);
//nums[0](); 0
//nums[1](); 1
//nums[2](); 2
//隔离变量作用域
(function(){
var name = "zs";
function a(){
name = ‘sss‘;
}
})();
(function(){
var name = "ls";
function a(){
name = ‘vvv‘;
}
})();
//计数器
//普通实现
var num = 0;
function countNum(){
num ++;
}
countNum();
console.log(num);
//闭包实现
var counter = (function(){
var counterPer = 0;
return function(){
return counterPer++;
}
})();
console.log(counter());
var counter=(function(){
//赋初值
var count=0;
//外部调用时形成闭包
return function(){
return count++;
}
})();
//声明私有变量
/*function People(){
this.name = ‘张三‘;
}
var p = new People();
console.log(p.name);*/
//直接可以.来进行访问,这是公有属性,安全性差
//私有属性是通过.访问不到的
var People = (function(){
var name = ‘‘;
function People(){
}
People.prototype = {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
}
}
return People;
})();
var p = new People();
//this
var test = ‘李四‘;
function th_test(){
console.log(this.test);
}
function bth_test(){
var test = ‘王五‘;
return function(){
console.log(this.test);
}
}
//this永远指向调用它的对象
js闭包
Posted 剑域柳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js闭包相关的知识,希望对你有一定的参考价值。
以上是关于js闭包的主要内容,如果未能解决你的问题,请参考以下文章