建立對象的方法

來源:互聯網
上載者:User

1、通過JSON建立對象

2、先new  Object,然後添加屬性和方法,缺點:會產生大量重複的代碼

var people = new OBject();people.name =  "aaaa";people.getName = function(){     alert('get the name:' +this.name);} 

3、通過對象字面量,缺點:會產生大量重複的代碼

var people = {    name: "aaaa",    getName: function(){        alert('get the name:'+this.name);    }}

4、原廠模式,缺點:不能識別對象的類型

function  createFunction(name){      var o = new Object();       o.name = name;       o.getName = function(){            alert('get the name: '+this.name);       }
return o;}

5、建構函式模式,缺點:不能實現方法的共用

function  People(name){     this.name = name;     this.getName = function(){          alert('get the name '+this.name);     }}

6、原型模式,缺點:有些屬性不需要共用

var Peopel = {}People.prototype = {    constructor:People,    name:"aaa",    getName:function(){         alert('the name is:' +this.name);          }}

7、組合使用建構函式模式和原型模式

function People(name){    this.name = name;}People.prototype = {    constructor:People;    getName: function(){         alert('the name is'+this.name);    }}

8、動態原型模式,這是一種較好的建立對象模式

1 function People(name){2      this.name = name;3      if(typeof this.getName != "function"){4            People.prototype.getName = function(){5                  alert('the name is:' +this.name);6            }7      }8 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.