javascript 继承之创建子类

        <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>

通过如上方式,就可以通过访问基类的属性,并且可以重写基类的方法。

转载于:https://www.cnblogs.com/xlhblogs/archive/2012/01/17/2324686.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值