1. 程式人生 > >es6學習五:類與繼承

es6學習五:類與繼承

before:

function Animal(name){
    this.name = name;
}
Animal.prototype.showName = function(){
    console.log(this.name);
}
var a = new Animal('Tom');
a.showName();
var a1 = new Animal('Jerry');
a1.showName();
function Animal(name){
    this.name = name;
}
Animal.showInfo = function(){
    console.log('hi');
};
Animal.prototype.showName = function(){
    console.log(this.name);
}
function Dog(name,color){
    Animal.call(this,name);
    this.color = color;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
Dog.prototype.showColor = function(){
    console.log(this.color);
}
let d = new Dog('doudou','yellow');
d.showName();
d.showColor();

now:

class Animal{
    // 靜態方法(靜態方法只能通過類名呼叫,不可以使用例項物件呼叫)
    static showInfo(){
        console.log('hi');
    }
    // 建構函式
    constructor(name){
        this.name = name;
    }
    //例項方法
    showName(){
        console.log(this.name);
    }
}
let a = new Animal('spike');
a.showName();
// a.showInfo();//報錯a.showInfo is not a function
Animal.showInfo();

// 類的繼承extends
class Dog extends Animal{
    constructor(name,color){
        super(name);//super用來呼叫父類
        this.color = color;
    }

    showColor(){
        console.log(this.color);
    }
}

let d = new Dog('doudou','yellow');
d.showName();
d.showColor();
// d.showInfo();
Dog.showInfo();