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>

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

  • 相关阅读:
    C#:正则表达式
    jsp:
    关于博客的设置
    登录注册案例—MongoDB数据库连接
    cookie封装
    博客样式
    自己的博客
    CentOS7 启动docker.service失败
    合并多个jar包,并通过私服依赖
    springboot+支付宝条码支付开发详解
  • 原文地址:https://www.cnblogs.com/xlhblogs/p/2324686.html
Copyright © 2011-2022 走看看