ES6 继承、多态简单demo

继承demo:

class Animal{
    constructor(shoutVoice, speed){
        this._shoutVoice = shoutVoice;
        this._speed = speed;
    }

    get speed(){
        return this._speed;
    }

    shout(){
        console.log(this._shoutVoice);
    }

    run(){
        console.log('本上仙的速度可是有' + this.speed);
    }
}

class Dog extends Animal{
    constructor(){
        super('汪汪汪', '10m/s');
    }

    gnawBone(){
        console.log('这是本狗最幸福的时候');
    }

    run(){
        console.log('本狗的速度可是有' + this._speed);
        super.run();
    }
}

class PoodleDog extends Dog{
    constructor(){
        super();
        this._breed = 'poodle';
    }

    get breed(){
        return this._breed;
    }
}

let poodleDog = new PoodleDog();
console.log(poodleDog.breed);
console.log(poodleDog.speed);
poodleDog.shout();
poodleDog.run()
poodleDog.gnawBone();


console.log:
poodle
10m/s
汪汪汪
本狗的速度可是有10m/s
本上仙的速度可是有10m/s
这是本狗最幸福的时候


多态demo:

class Animal{
    eat(food){
        console.log('"' + this.constructor.name + '"类没有eat()方法.');
    }
}

class Snake extends Animal{}

class Dog extends Animal{
    eat(food){
        console.log('本狗在啃' + food);        
    }
}

class Cat extends Animal{
    eat(food){
        console.log('这只猫在吃' + food);
    }
}

let snake = new Snake();
snake.eat('老鼠');

let dog = new Dog();
dog.eat('骨头');

let cat = new Cat();
cat.eat('鱼');

console.log:
"Snake"类没有eat()方法.
本狗在啃骨头
这只猫在吃鱼








猜你喜欢

转载自blog.csdn.net/w1019945543/article/details/78247541