javascript之對象學習筆記(二)–對象原型,繼承

來源:互聯網
上載者:User

這裡使用rectangle()函數作為例子

1.簡單函數

 function rectangle(w,h){

this.width = w;

this.height = h;     

   }

var test = new rectangle(1,2);建立簡單rectangle對象,包含width,height屬性

額外定義一個計算面積的函數將test對象以參數形式傳入

function getRecArea(rec){ 

return rec.width * rec.height;  

}

console.log( getRecArea(test) );

此時就可以簡單計算任意簡單矩形面積,但上述不符合物件導向編程設計思想,應該將方法也包含進 " 類 "

function rectangle(w,h){

this.width = w;

this.height = h;    

this.area = function (){return this.width * this.height} 

 }

console.log( test.area())

此時已經是一個很友好的解決方案,但還不是最佳化的,每建立一個rectanlge對象的時候變的只是width和height參數,而裡面arec函數在每個rectanlge對象裡面都一樣,這讓我想到java裡面的繼承機制,java裡面繼承自基類,javascript裡面每個對象又有prototype對象屬性(其實在建立對象後就預設初始化了該對象的prototype屬性值,prototype初始化是一個對象並包含一個constructor屬性,這也是每個對象為什麼都有constructor的原因),
添加自prototype裡的函數或屬性都會成為被初始化對象的屬性

 function rectangle(w,h){

this.width = w;

this.height = h;

}

rectangle.prototype.arec = function () { return this.width* this .height;} //總結:將不變的屬性放在prototype裡面是很好的解決方案

2.拓展內建類型

  不僅使用者自訂的函數有prototype,javascript內建的String ,Date等內建類 也有prototype屬性;

  執行個體:判斷字串是否以指定字元結尾

 String.prototype.isEndWith = function(c){

return (c == this.charAt(this.length-1))

 }

var s = " STRINGc";

console.log(s.isEend());

相關文章

聯繫我們

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