zoukankan      html  css  js  c++  java
  • js继承

    //练习js继承(组合继承:原型继承和构造函数继承的组合)
    function Polygon(length, area) {
        this.length = length;
        this.area = area;
    }
    Polygon.prototype = {
        constructor: Polygon,
        getLength: function () { console.log(this.length);console.log(" Polygon--getLength()!"); },
        getArea: function () { console.log(this.area); },
        sayHello: function () { console.log("Hi,I'm Polygon!");}
    }
    function Triangle(length, area) {
        //继承属性
        Polygon.call(this, length, area);//在子类对象上调用父类构造函数
       //添加新属性
       //this.a=a;
    
    }
    //继承方法
    Triangle.prototype = new Polygon();
    //注意:通过原型链实现继承时,不能使用对象字面量创建原型的方法,会导致重写原型链
    /*Triangle.prototype = {
        constructor: Triangle,
        getLength: function () { console.log("Triangle length is " + this.length); },
        getArea: function () { console.log("Triangle area is " + this.area); }
    }*/
    
    Triangle.prototype.constructor = Triangle;//设置constructor属性
    //重写父类方法
    Triangle.prototype.getLength = function () {
        //Polygon.prototype.getLength.call(this);
        console.log("Triangle length is " + this.length);
    };
    
    
    Triangle.prototype.getArea = function () {
        console.log("Triangle area is " + this.area);
    };
    //添加新方法
    Triangle.prototype.sayTriangle = function () { console.log("Hi,I'm Triangle!"); };
    
    
    var polygon1 = new Polygon(1, 2);
    polygon1.getLength();
    polygon1.getArea();
    
    var triangle1 = new Triangle(12, 16);
    
    //调用子类重写的方法
    triangle1.getLength();
    triangle1.getArea();
    //调用子类的新方法
    triangle1.sayTriangle();
    //调用父类未被重写的方法
    triangle1.sayHello();
    //调用父类被重写的方法
    Polygon.prototype.getLength.call(triangle1);

    console打印信息:

    1
    Polygon--getLength()!
    2
    Triangle length is 12
    Triangle area is 16
    Hi,I'm Triangle!
    Hi,I'm Polygon!
    12
    Polygon--getLength()!

  • 相关阅读:
    unity编辑器扩展
    unity给localRotation赋值
    ASp.net常用服务
    二叉树
    Photon Server类函数介绍
    线程间操作无效: 从不是创建控件的线程访问它的三种方法
    使用vs的输出窗口进行调试输出数据
    Bmob后端云之云数据库的使用
    软件设计的七大原则
    Unite Beijing 2018 参会简要分享
  • 原文地址:https://www.cnblogs.com/Yogurshine/p/6927342.html
Copyright © 2011-2022 走看看