zoukankan      html  css  js  c++  java
  • 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>

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

  • 相关阅读:
    Linux基础命令grep(如何过滤字符串)
    Linux基础命令wc(如何统计文件的行数?如何统计文件的字节数?)
    Linux基础命令tr(如何替换字符)
    django4
    django3
    django2
    django1
    jQuery2
    jQuery1
    事件
  • 原文地址:https://www.cnblogs.com/xlhblogs/p/2324686.html
Copyright © 2011-2022 走看看