《javascript進階程式設計》學習筆記(六):javascript 實作類別的繼承

來源:互聯網
上載者:User
 

廢話不說,直接說類的最好的繼承方式:
混合方式,即用對象冒充繼承建構函式的屬性,用原型鏈繼承prototype對象的方法:
看了例子就明白:
function ClassA(sColor){
 this.color = sColor;
}
ClassA.prototype.sayColor = function (){
 alert(this.color);
}

function ClassB(sColor,sName){
 ClassA.call(this,sColor);  //冒充繼承,call
 this.name = sName;
}
ClassB.prototype = new ClassA();//原型鏈繼承
ClassB.prototype.sayName = function (){
 alert(this.name);
}

var objA = new ClassA("red");
var objB = new ClassB("blue","kit");
objA.sayColor();//outputs "red"
objB.sayColor();//outputs "blue"
objB.sayName(); //outputs "kit"

更為實際的例子:
基類:多邊形Polygon (屬性:side--邊的個數;方法:getArea()--計算面積)
子類1:三角形Triangle(增加屬性:base--底,height--高 ;重寫方法:getArea()--低×高/2)
子類2:矩形Rectangle(增加屬性:length--長,width--寬;重寫方法:getArea()--長×寬)

UML

 

//類Polygon:
function Polygon(iSides){
 this.side = iSides;
}
Polygon.prototype.getArea = function (){
 return 0;
}
//類Triangle:
function Triangle(iBase,iHeight){
 Polygon.call(this,3);
 this.base = iBase;
 this.height = iHeight;
}
Triangle.prototype = new Polygon();
Triangle.prototype.getArea = function(){
 return 0.5 * this.base * this.height;
}

//類:Rectangle
function Rectangle(iLength,iWidth){
 Polygon.call(this,4);
 this.length = iLength;
 this.width = iWidth;
}
Rectangle.prototype = new Polygon();
Rectangle.prototype.getArea = function(){
 return this.length * this.width;
}

//測試:
var objTriangle = new Triangle(5,6);
var objRectangle = new Rectangle(22,10);

alert(objTriangle.side);
alert(objTriangle.getArea());


alert(objRectangle.side);
alert(objRectangle.getArea());

相關文章

聯繫我們

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