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>

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

  • 相关阅读:
    tcp 粘包 和 TCP_NODELAY 学习
    分解抓取的包文件代码实现学习
    谨慎使用多线程中的fork 学习!!!!
    面试题
    Java并发编程:Lock
    为什么匿名内部类参数必须为final类型
    sql 面试题
    java hashCode方法返回值
    数组初始化
    Java内存模型
  • 原文地址:https://www.cnblogs.com/xlhblogs/p/2324686.html
Copyright © 2011-2022 走看看