JavaScript物件導向編程(6)利用原型鏈實現繼承

來源:互聯網
上載者:User

JavaScript物件導向編程(6)利用原型鏈實現繼承

繼承是物件導向的特性之一,繼承的主要目的就是為了重用。子類能複用父類的屬性或者行為,可以極大地簡化子類,避免重複定義。

繼承的特徵1.子物件擁有父物件的屬性和方法

繼承特徵2:子物件“是一個”父物件,具備“is-a”的特點,
如人是動物,那麼人就是動物的子類,體現在對象上,一個人必然有一個指向動物執行個體的引用

子類的prototype指向父類的一個執行個體,就完成了繼承,因為子類的執行個體上具備了父類執行個體的屬性和行為。

Java中子類執行個體有super關鍵字指向父類執行個體,在繼承上,所有物件導向語言都差不多的。


//形狀function Shape(){this.name = 'shape';this.toString = function() {return this.name;};}//2d形狀function TwoDShape(){this.name = '2D shape';}//三角形function Triangle(side, height) {this.name = 'Triangle';this.side = side;this.height = height;this.getArea = function(){return this.side * this.height / 2;};}//繼承的特徵1.子物件擁有父物件的屬性和方法TwoDShape.prototype = new Shape();Triangle.prototype = new TwoDShape();//修複TwoDShape.prototype.constructor = TwoDShape;Triangle.prototype.constructor = Triangle;var my = new Triangle(5, 10);alert(my.toString());//自己沒有toString方法,繼承而來alert(my.constructor);/*繼承特徵2:子物件“是一個”父物件,具備“is-a”的特點,如人是動物,那麼人就是動物的子類,體現在對象上,一個人必然有一個指向動物執行個體的引用*/alert(my instanceof TwoDShape);//有繼承的特性alert(my instanceof Shape);


聯繫我們

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