《javascript高级程序设计》学习笔记(六):javascript 实现类的继承

 

废话不说,直接说类的最好的继承方式:
混合方式,即用对象冒充继承构造函数的属性,用原型链继承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());

posted @ 2008-05-08 20:23  MichaelChen  阅读(277)  评论(0编辑  收藏  举报