本文通过举例,由浅入深的讲解了解决js函数闭包内存泄露问题的办法,分享给大家供大家参考,具体内容如下
原始代码:
function cars(){ this.name = benz; this.color = [white,black];}cars.prototype.saycolor = function(){ var outer = this; return function(){ return outer.color };};var instance = new cars();console.log(instance.saycolor()())
优化后的代码:
function cars(){ this.name = benz; this.color = [white,black];}cars.prototype.saycolor = function(){ var outercolor = this.color; //保存一个副本到变量中 return function(){ return outercolor; //应用这个副本 }; outcolor = null; //释放内存};var instance = new cars();console.log(instance.saycolor()())
稍微复杂一点的例子:
function inheritprototype(subtype,supertype){ var prototype = object(supertype.prototype); prototype.constructor = subtype; subtype.prototype = prototype;}function cars(){ this.name = benz; this.color = [white,black];}cars.prototype.saycolor = function(){ var outer = this; return function(){ return outer.color; };};function car(){ cars.call(this); this.number = [321,32];}inheritprototype(car,cars);car.prototype.saynumber = function(){ var outer = this; return function(){ return function(){ return outer.number[outer.number.length - 1]; } };};var instance = new car();console.log(instance.saynumber()()());
首先,该例子组合使用了构造函数模式和原型模式创建cars 对象,并用了寄生组合式继承模式来创建car 对象并从cars 对象获得属性和方法的继承;
其次,建立一个名为instance 的car 对象的实例;instance 实例包含了saycolor 和saynumber 两种方法;
最后,两种方法中,前者使用了一个闭包,后者使用了两个闭包,并对其this 进行修改使其能够访问到this.color 和this.number。
这里存在内存泄露问题,优化后的代码如下:
function inheritprototype(subtype,supertype){ var prototype = object(supertype.prototype); prototype.constructor = subtype; subtype.prototype = prototype;}function cars(){ this.name = benz; this.color = [white,black];}cars.prototype.saycolor = function(){ var outercolor = this.color; //这里 return function(){ return outercolor; //这里 }; this = null; //这里};function car(){ cars.call(this); this.number = [321,32];}inheritprototype(car,cars);car.prototype.saynumber = function(){ var outernumber = this.number; //这里 return function(){ return function(){ return outernumber[outernumber.length - 1]; //这里 } }; this = null; //这里};var instance = new car();console.log(instance.saynumber()()());
以上就是为大家分享的解决方法,希望对大家的学习有所帮助。