解决js函数闭包内存泄露问题的办法
本文通过举例,由浅入深的讲解了解决js函数闭包内存泄露问题的办法,分享给大家供大家参考,具体内容如下
原始代码:
functionCars(){
this.name="Benz";
this.color=["white","black"];
}
Cars.prototype.sayColor=function(){
varouter=this;
returnfunction(){
returnouter.color
};
};
varinstance=newCars();
console.log(instance.sayColor()())
优化后的代码:
functionCars(){
this.name="Benz";
this.color=["white","black"];
}
Cars.prototype.sayColor=function(){
varouterColor=this.color;//保存一个副本到变量中
returnfunction(){
returnouterColor;//应用这个副本
};
outColor=null;//释放内存
};
varinstance=newCars();
console.log(instance.sayColor()())
稍微复杂一点的例子:
functioninheritPrototype(subType,superType){
varprototype=Object(superType.prototype);
prototype.constructor=subType;
subType.prototype=prototype;
}
functionCars(){
this.name="Benz";
this.color=["white","black"];
}
Cars.prototype.sayColor=function(){
varouter=this;
returnfunction(){
returnouter.color;
};
};
functionCar(){
Cars.call(this);
this.number=[321,32];
}
inheritPrototype(Car,Cars);
Car.prototype.sayNumber=function(){
varouter=this;
returnfunction(){
returnfunction(){
returnouter.number[outer.number.length-1];
}
};
};
varinstance=newCar();
console.log(instance.sayNumber()()());
首先,该例子组合使用了构造函数模式和原型模式创建Cars对象,并用了寄生组合式继承模式来创建Car对象并从Cars对象获得属性和方法的继承;
其次,建立一个名为instance的Car对象的实例;instance实例包含了sayColor和sayNumber两种方法;
最后,两种方法中,前者使用了一个闭包,后者使用了两个闭包,并对其this进行修改使其能够访问到this.color和this.number。
这里存在内存泄露问题,优化后的代码如下:
functioninheritPrototype(subType,superType){
varprototype=Object(superType.prototype);
prototype.constructor=subType;
subType.prototype=prototype;
}
functionCars(){
this.name="Benz";
this.color=["white","black"];
}
Cars.prototype.sayColor=function(){
varouterColor=this.color;//这里
returnfunction(){
returnouterColor;//这里
};
this=null;//这里
};
functionCar(){
Cars.call(this);
this.number=[321,32];
}
inheritPrototype(Car,Cars);
Car.prototype.sayNumber=function(){
varouterNumber=this.number;//这里
returnfunction(){
returnfunction(){
returnouterNumber[outerNumber.length-1];//这里
}
};
this=null;//这里
};
varinstance=newCar();
console.log(instance.sayNumber()()());
以上就是为大家分享的解决方法,希望对大家的学习有所帮助。