ES6 继承、多态简单demo

来源:互联网 发布:unity3d vector2 编辑:程序博客网 时间:2024/06/02 02:31

继承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:poodle10m/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()方法.本狗在啃骨头这只猫在吃鱼







原创粉丝点击