js物件導向-建立對象

來源:互聯網
上載者:User

標籤:blog   java   使用   io   ar   div   cti   log   new   

原廠模式

原廠模式通過在函數中建立一個對象(原材料),然後通過給這個對象添加屬性和方法(加工),最後返回這個對象(出廠)。

// 1.原廠模式function createPerson(name,age,job) {//1.原材料var o = new Object(); //2.加工 o.name = name;o.age = age;o.job = job;o.sayName = function() {alert(this.name);};//3.出廠return o;}var yoomin = createPerson(‘yoomin‘,24,‘programmer‘);  // 調用,沒有new
  建構函式模式

建構函式是通過給this添加屬性和方法,在new的時候才返回一個對象,建構函式本身是沒有傳回值的。

// 2.建構函式模式function Person(name,age,job) {this.name = name;this.age = age;this.job = job;this.sayAge = function() {alert(this.age);}}var Jay = new Person(‘Jay‘,30,‘singer‘);  //調用

 

建構函式方式與原型方式組合

使用建構函式方式定義屬性,用原型方式定義方法和共用變數:

建構函式定義屬性:

function Person(name,age,job) {// 建構函式模式定義執行個體屬性this.name = name;this.age = age;this.job = job;}

  原型方式定義方法:

Person.prototype = {//原型模式定義方法和共用屬性constructor: Person,  //重寫原型改變了constructor,修正回來sayName:function() {alert(this.name);},sayJob:function() {alert(this.job);}}

  注意:用字面量方式定義prototype,會改變prototype的constructor指向,需要修正。

建立對象:

var Kelly = new Person(‘Kelly‘,35,‘singer‘);  //調用Kelly.sayName();  //Kelly

  

js物件導向-建立對象

聯繫我們

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