<script type="text/javascript">
function Ploygon(side) //父类:主要属性有多边形的边数和获得多边形的面积的方法。
{
this.sides = side;
}
Ploygon.prototype.getArea = function(){
return 0;
}
function Triangle(IBase,IWidth) //三角形
{
Ploygon.call(this,3); //通过,function.call()将多边形的边数传递给基类
this.base = IBase;
this.width = IWidth;
}
Triangle.prototype = new Ploygon(); //继承基类
Triangle.prototype.getArea = function() //用本身的getArea()方法覆盖父类的getArea()方法
{
return 0.5*this.base*this.width;
}
function Rectangle(ILength,IWidth)
{
Ploygon.call(this,4);
this.length = ILength;
this.width = IWidth;
}
Rectangle.prototype = new Ploygon();
Rectangle.prototype.getArea = function()
{
return this.length*this.width;
}
var tri=new Triangle(6,10);
alert(tri.sides);
alert(tri.getArea());
var rec = new Rectangle(10,20);
alert(rec.sides);
alert(rec.getArea())
</script>
通过如上方式,就可以通过访问基类的属性,并且可以重写基类的方法。