閉包
基本概念
當(dāng)<em>內(nèi)部函數(shù)</em>被保存到<em>外部</em> 時(shí)尤筐,將會(huì)一定生成閉包。閉包會(huì)導(dǎo)致原有作用域鏈不釋放洞就,造成內(nèi)存泄露盆繁。
閉包的作用
- 1.實(shí)現(xiàn)共有變量
function add (){
var count =0;
function demo () {
count++:
console.log(count);
}
return demo;
}
var counter = add();
counter();
counter();
counter();--------會(huì)一直執(zhí)行
- 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.私有化變量
//利用閉包旬蟋,實(shí)現(xiàn)變量私有化
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.命名空間:模塊化開(kāi)發(fā)油昂,防止變量沖突(補(bǔ)充)
- 管理變量,防止污染全局咖为,適用于模塊化開(kāi)發(fā)
var init = (function(){
var abc =123;
//利用閉包實(shí)現(xiàn)變量私有化秕狰。
function callName (){
console.log(name);
}
return function(){
callName();
}
}())
init();//init啟動(dòng)時(shí)稠腊,就會(huì)啟動(dòng)callName