1. 程式人生 > >幾個閉包記憶體洩漏的優化方案!

幾個閉包記憶體洩漏的優化方案!

本文通過舉例,由淺入深的講解了解決js函式閉包記憶體洩露問題的辦法,分享給大家供大家參考,具體內容如下

原始碼:

<span style="font-size:14px;">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()())</span>

優化後:
<span style="font-size:14px;">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()())</span>

舉例:

<span style="font-size:14px;">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()()());</span>

首先,該例子組合使用了建構函式模式和原型模式建立Cars 物件,並用了寄生組合式繼承模式來建立Car 物件並從Cars 物件獲得屬性和方法的繼承;

其次,建立一個名為instance 的Car 物件的例項;instance 例項包含了sayColor 和sayNumber 兩種方法;

最後,兩種方法中,前者使用了一個閉包,後者使用了兩個閉包,並對其this 進行修改使其能夠訪問到this.color 和this.number。

這裡存在記憶體洩露問題,優化後的程式碼如下:

<span style="font-size:14px;">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()()());</span>