zoukankan      html  css  js  c++  java
  • 3.class继承及案例——ES6类和继承

    // es5的继承
    
    function Animal(name,color){
        this.name = name;
        this.color = color;
    }
    
    Animal.prototype.eat = function(){
        console.log(this.name + ' is eating');
    }
    Animal.prototype.sleep = function(){
        console.log(this.name + ' is sleeping');
    }
    
    //继承
    function Rabbit(name,color,age){
        //调用父类构造
        Animal.call(this,arguments);
        this.age = age;
    }
    
    function foo(){}
    
    foo.prototype = Animal.prototype;
    Rabbit.prototype = new foo();
    Rabbit.prototype.constructor = Rabbit;
    
    let rabbit = new Rabbit('大白','white',10);
    rabbit.eat();
    rabbit.sleep();
    console.log(rabbit);
    
    
    //es6
    class Animal{
        constructor(name,color){
            this.name = name;
            this.color = color;
        }
    
        eat(){
            console.log(this.name + ' is eating');
        }
        sleep(){
            console.log(this.name + ' is slepping');
        }
    }
    
    class Rabbit extend Animal{
        constructor(name,color,age){
            //子类中通过super调用父类的构造函数,一定要放在第一行
            super(name,color);
            this.age = age;
        }
        eat(){
            console.log('我是自己的eat');//这里自已如果有就覆盖父亲的
        }
        test(){
            super.eat();
        }
    }
    
    let rab = new Rabbit('大白','white',10);
    rab.eat();
    rab.sleep();
    rab.test();
    console.log(rab)
  • 相关阅读:
    随手记
    boost::asio::udp 异步
    boost::asio::tcp 异步
    boost::asio::tcp 同步
    QML::MouseArea
    boost::concurrent::sync_queue
    std::chrono::时钟
    数据结构::队列
    数据结构::栈
    数据结构::线性表
  • 原文地址:https://www.cnblogs.com/lisa2544/p/15666785.html
Copyright © 2011-2022 走看看