本文通过举例,由浅入深的讲解了解决js函数闭包内存泄露问题的办法,分享给大家供大家参考,具体内容如下
原始代码:
console.log(instance.sayColor()())
优化后的代码:
console.log(instance.sayColor()())
稍微复杂一点的例子:
<div class="jb51code">
<pre class="brush:js;">
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()()());