This article explains how to solve the problem of js function closure memory leakage through examples, from shallow to deep, and shares it with everyone for your reference. The specific content is as follows
Original code:
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()())
Optimized code:
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()())
A slightly more complicated example:
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()()());
First of all, this example uses a combination of the constructor pattern and the prototype pattern to create the Cars object, and uses the parasitic combined inheritance pattern to create the Car object and obtain the inheritance of properties and methods from the Cars object;
Secondly, create an instance of the Car object named instance; the instance contains two methods: sayColor and sayNumber;
Finally, of the two methods, the former uses one closure, and the latter uses two closures, and modifies its this so that it can access this.color and this.number.
There is a memory leak problem here. The optimized code is as follows:
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()()());
The above is the solution shared with everyone. I hope it will be helpful to everyone's study.