JS物件導向的程式設計 - 高設

來源:互聯網
上載者:User

標籤:style   c   class   blog   code   java   

 1 //原廠模式 2     function createPerson (name, age, job){ 3         var o = new Object(); 4         o.name = name; 5         o.age = age; 6         o.job = job; 7  8         o.sayName = function (){ 9             alert(this.name);10         }11         return o;12     }13 14     var sam = createPerson("sam", 18, "web front");15 16 17 //建構函式模式18     function Person (name, age, job){19         this.name = name;20         this.age = age;21         this.job = job;22         this.sayName = function (){23             alert(this.name);24         }25     }26 27     var david = new Person("david",18,"student");

 

原型模式

我們建立的每一個函數都有一個prototype(原型)屬性,這個屬性是一個指標,指向一個對象,而這個對象的用途是可包含可以由特定類型的所有執行個體共用的屬性和方法;(還不會自己總結- -)

 

缺點:建構函式建立的每一個執行個體都會建立每一個執行個體的function執行個體,而每一個執行個體的function執行個體都不相等;(解決方案:高射147頁,第三版)

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

 

建構函式

建構函式其實也是普通的函數對象,建構函式與其他函數唯一的區別就是:當它通過 new操作符調用時,它就可以變成建構函式

將建構函式當作普通函數使用時,建構函式會將建構函式的參數添加給全域對象的屬性(window);

hasOwnProperty()方法 檢測屬性是執行個體建立的還是繼承原型

 1 Person2.prototype.name = "sam"; 2     Person2.prototype.age = 18; 3     Person2.prototype.sayName = function (){ 4         alert(this.name); 5     } 6  7     var person1 = new Person2(); 8     var person2 = new Person2(); 9     alert(person1.hasOwnProperty(‘name‘)); // false;10 11     person1.name = "david";12     alert(person1.name); // "david" ----來自執行個體;13     alert(person1.hasOwnProperty(‘name‘)); // true;14 15     alert(person2.name); // "sam" ----來自原型;16     alert(person2.hasOwnProperty(‘name‘)); // false;17 18     delete person1.name;19     alert(person1.name); // "sam" ----來自原型20     alert(person2.hasOwnProperty(‘name‘)); // true;

 

 

...........睡覺了- -明天再繼續更新

 

 

聯繫我們

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