js建立對象幾種方式的優缺點對比_javascript技巧

來源:互聯網
上載者:User

比較js中建立對象的幾種方式

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

缺點:①無法確定對象的類型(因為都是Object)。

   ②建立的多個對象之間沒有關聯。

 2.建構函式

function createObj(name, sex){    this.name = name;    this.sex = sex;    this.sayName = function(){      alert(this.name);    }  }  var person = new createObj('Tom', 'man');

缺點:①多個執行個體重複建立方法,無法共用。

     ②多個執行個體都有sayName方法,但均不是同一個Function的執行個體。 

3.原型方法

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

缺點:①無法傳入參數,不能初始化屬性值。

     ②如果包含參考型別的值時,改變其中一個執行個體的值,則會在所有執行個體中體現。 

4.組合式(建構函式+原型方法)推薦使用

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

優點:建構函式共用執行個體屬性,原型共用方法和想要共用的屬性。可傳遞參數,初始化屬性值。 

5.動態原型方法

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

說明:if語句中只會調用一次,就是在碰到第一個執行個體調用方法時會執。此後所有執行個體都會共用該方法。在動態原型方法下,不能使用對象字面量重寫原型。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.