闭包
基本概念
当<em>内部函数</em>被保存到<em>外部</em> 时,将会一定生成闭包。闭包会导致原有作用域链不释放,造成内存泄露。
闭包的作用
- 1.实现共有变量
function add (){
var count =0;
function demo () {
count++:
console.log(count);
}
return demo;
}
var counter = add();
counter();
counter();
counter();--------会一直执行
- 2.可以做缓存
function eater () {
var food = "";
var obj = {
eat:function () {
console.log('i am eat ' + food)
food="";
},
push:function(myFood){
food = myFood;
//是food,不用this.food
}
}
return obj;
}
var e = eater();
e.push("apple");
e.eat();
- 3.私有化变量
//利用闭包,实现变量私有化
function Deng (name,wife){
var prepareWife = "xiaozhang";
this.name= name;
this.wife = wife;
this.divorce =function(){
this.wife=prepareWife;
}
this.changeWife = function(target){
prepareWife=target;
}
this.sayPrepareWife =function(){
console.log(prepareWife);
}
var deng = new Deng("deng","xiaoli");
console.log(deng.prepareWife);//undefined
- 4.命名空间:模块化开发,防止变量冲突(补充)
- 管理变量,防止污染全局,适用于模块化开发
var init = (function(){
var abc =123;
//利用闭包实现变量私有化。
function callName (){
console.log(name);
}
return function(){
callName();
}
}())
init();//init启动时,就会启动callName