// 父>>>子继承classEnemy{constructor(power){this.power=power
}attack=()=>console.log(`i'm attacking with a power of ${this.power}!`)}classAlienextendsEnemy{constructor(name,phrase,power){super(power)this.name=name;this.phrase=phrase;this.species='alien'}fly=()=>console.log('zzzzzzzzzgggggzzzz');sayPhrase=()=>console.log(this.phrase)}const alien1=newAlien('Ali','i am this alien',10)
console.log('alien',alien1)
alien1.attack();
在子类中,我们使用 extends 关键字来声明我们需要继承父类。在 constructor 方法中,我们必须声明 “power” 参数并且使用super函数,来表示属性是在父元素中声明的。
当我们实例化新的对象的时候,其实我们传入了声明在 constructor 函数里的参数。哒哒!我们就可以在实例中访问在父类中声明的属性和方法了。
// 祖>>>>子 继承classCharacter{constructor(speed){this.speed=speed;}move=()=>console.log(`i'm moving at this speed of ${this.speed}`)}classEnemyextendsCharacter{constructor(power,speed){super(speed);this.power=power
}attack=()=>console.log(`i'm attacking with a power of ${this.power}`)}classAlienextendsEnemy{constructor(name,phrase,power,speed){super(power,speed)this.name=name;this.phrase=phrase;this.species='alien'}fly=()=>console.log('xxxxxxxxxxxxx');sayPhrase=()=>console.log(this.phrase)}const alien1=newAlien('Ali','i am ali this alien!',10,50)
alien1.move();