码迷,mamicode.com
首页 > Web开发 > 详细

js闭包

时间:2018-03-12 16:51:14      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:body   [1]   return   post   i++   setname   ons   func   安全   

//闭包引起的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闭包

标签:body   [1]   return   post   i++   setname   ons   func   安全   

原文地址:https://www.cnblogs.com/staticed/p/8549582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!