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)
原文地址:https://www.cnblogs.com/lisa2544/p/15666785.html