DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 解決js函數閉包內存洩露問題的辦法
解決js函數閉包內存洩露問題的辦法
編輯:關於JavaScript     

本文通過舉例,由淺入深的講解了解決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()()());

以上就是為大家分享的解決方法,希望對大家的學習有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved