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>

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

  • 相关阅读:
    在阿里云centos7.6上部署vue.js2.6前端应用
    gRPC
    Docker
    ES6、ES7、ES8、ES9、ES10
    HTTPS工作原理 HTTP协议数据结构分析 HTTP和HTTPS协议的不同之处
    SpringBean的工作原理
    Nginx负载均衡高可用---架构
    集群的负载策略
    redis 和 memcached的区别
    Django的基础教程
  • 原文地址:https://www.cnblogs.com/xlhblogs/p/2324686.html
Copyright © 2011-2022 走看看