本文透過舉例,由淺入深的講解了解決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()()());
以上就是為大家分享的解決方法,希望對大家的學習有所幫助。