欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js創(chuàng)建對(duì)象幾種方式的優(yōu)缺點(diǎn)對(duì)比

 更新時(shí)間:2016年09月28日 16:54:08   作者:小_前端  
這篇文章主要對(duì)比了js創(chuàng)建對(duì)象幾種方式的優(yōu)缺點(diǎn),感興趣的小伙伴們可以參考一下

比較js中創(chuàng)建對(duì)象的幾種方式

1.工廠模式

function createObj(name, sex){
    var obj = new Object();
    obj.name = name;
    obj.sex = sex;
    obj.sayName = function(){
      alert(this.name);
    }
    return obj;
  }

var person = createObj('Tom', 'man');

缺點(diǎn):①無(wú)法確定對(duì)象的類型(因?yàn)槎际荗bject)。

   ②創(chuàng)建的多個(gè)對(duì)象之間沒(méi)有關(guān)聯(lián)。

 2.構(gòu)造函數(shù)

function createObj(name, sex){
    this.name = name;
    this.sex = sex;
    this.sayName = function(){
      alert(this.name);
    }
  }

  var person = new createObj('Tom', 'man');

缺點(diǎn):①多個(gè)實(shí)例重復(fù)創(chuàng)建方法,無(wú)法共享。

     ②多個(gè)實(shí)例都有sayName方法,但均不是同一個(gè)Function的實(shí)例。 

3.原型方法

function createObj(){}

  createObj.prototype.name = 'Tom';
  createObj.prototype.sex = 'man';
  createObj.prototype.sayName = function(){
    alert(this.name);
  }

var person = new createObj();

缺點(diǎn):①無(wú)法傳入?yún)?shù),不能初始化屬性值。

     ②如果包含引用類型的值時(shí),改變其中一個(gè)實(shí)例的值,則會(huì)在所有實(shí)例中體現(xiàn)。 

4.組合式(構(gòu)造函數(shù)+原型方法)推薦使用

function createObj(name, sex){
  this.name = name;
  this.sex = sex;
 }
 createObj.prototype.sayName = function(){
  alert(this.name);
 }

 var person = new createObj('Tom', 'man');

優(yōu)點(diǎn):構(gòu)造函數(shù)共享實(shí)例屬性,原型共享方法和想要共享的屬性??蓚鬟f參數(shù),初始化屬性值。 

5.動(dòng)態(tài)原型方法

function createObj(name, sex){
  this.name = name;
  this.sex = sex;
  if(typeof this.sayName != 'function'){
   createObj.prototype.sayName = function(){
    alert(this.name);
   }
  }
 }

 var person = new createObj('Tom', 'man');

說(shuō)明:if語(yǔ)句中只會(huì)調(diào)用一次,就是在碰到第一個(gè)實(shí)例調(diào)用方法時(shí)會(huì)執(zhí)。此后所有實(shí)例都會(huì)共享該方法。在動(dòng)態(tài)原型方法下,不能使用對(duì)象字面量重寫(xiě)原型。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論