JS 建立對象的7種方法(一)

來源:互聯網
上載者:User

標籤:

1.原廠模式(Factory)

 1 function createPerson(name, age, title){ 2     var o = new Object(); 3     o.name = name; 4     o,age = age; 5     o.title = title; 6     o.sayName = function(){ 7         alert(this.name); 8     } 9     return o;10 }   11 12 var person1 = createPerson("Greg", 30, "Doctor");13 var person2 = createPerson("Lisa", 20, "Teacher");  

 原廠模式不能識別對象的類型。

2.建構函式模式(Constructor)

 1 function Person(name, age, job){ 2     this.name = name; 3     this.age = age; 4     this.job = job; 5     this.sayName = function(){ 6         alert(this.name); 7     } 8 } 9 var person1 = new Person("Nicholas", 18, "Software Engineer");10 var person2 = new Person("Greg", 27, "Doctor");   

 按照慣例,建構函式始終都應以一個大寫字母開頭。

 要建立一個Person的新執行個體,必須使用new操作符。

 person1和person2分別儲存著Person的一個不同的執行個體,這兩個對象都有一個constructor屬性,該屬性指向Person:

alert(person1.constructor == Person)  //truealert(person2.constructor == Person)  //true

 建構函式的問題: 建構函式中的所有方法都要在每個執行個體上重新建立一遍。

alert(person1.sayName == person2.sayName);    //false

 

JS 建立對象的7種方法(一)

聯繫我們

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