亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

解決js函數(shù)閉包內(nèi)存泄露問(wèn)題的辦法

 更新時(shí)間:2016年01月25日 10:26:40   作者:billyangg  
這篇文章主要通過(guò)舉例介紹了解決js函數(shù)閉包內(nèi)存泄露問(wèn)題的辦法,感興趣的小伙伴們可以參考一下

本文通過(guò)舉例,由淺入深的講解了解決js函數(shù)閉包內(nèi)存泄露問(wèn)題的辦法,分享給大家供大家參考,具體內(nèi)容如下

原始代碼:

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()())

優(yōu)化后的代碼:

function Cars(){
  this.name = "Benz";
  this.color = ["white","black"];
}
Cars.prototype.sayColor = function(){
  var outerColor = this.color; //保存一個(gè)副本到變量中
  return function(){
    return outerColor; //應(yīng)用這個(gè)副本
  };
  outColor = null; //釋放內(nèi)存
};

var instance = new Cars();
console.log(instance.sayColor()())

稍微復(fù)雜一點(diǎn)的例子:

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()()());

首先,該例子組合使用了構(gòu)造函數(shù)模式和原型模式創(chuàng)建Cars 對(duì)象,并用了寄生組合式繼承模式來(lái)創(chuàng)建Car 對(duì)象并從Cars 對(duì)象獲得屬性和方法的繼承;

其次,建立一個(gè)名為instance 的Car 對(duì)象的實(shí)例;instance 實(shí)例包含了sayColor 和sayNumber 兩種方法;

最后,兩種方法中,前者使用了一個(gè)閉包,后者使用了兩個(gè)閉包,并對(duì)其this 進(jìn)行修改使其能夠訪(fǎng)問(wèn)到this.color 和this.number。

這里存在內(nèi)存泄露問(wèn)題,優(yōu)化后的代碼如下:

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()()());

以上就是為大家分享的解決方法,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

最新評(píng)論