js类的继承写法

继承相关注意事项:
1.一个子类只能继承一个父类,不可以继承多个父类。虽然确实有相应的技巧来解决这个问题。
2'你可以根据需求扩展继承链,设置父类、祖父类、太祖父类等。
如果子类从父类继承一些属性,必须首先使用super()函数并将父类属性传参,然后再设定子类自己的属性。
3.在继承的时候,所有父类的方法和属性都会被子类继承,我们并不能决定继承哪些,不继承哪些。(就像我们不能决定从我们的父母那里继承哪些美德和缺点一样)。
4.子类可以覆盖掉父类的属性和方法。
// 父>>>子继承
class Enemy{
    constructor(power){
        this.power=power
    }
    attack=()=>console.log(`i'm attacking with a power of ${this.power}!`)
}
class Alien extends Enemy{
    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=new Alien('Ali','i am this alien',10)
console.log('alien',alien1)
alien1.attack();

在子类中,我们使用 extends 关键字来声明我们需要继承父类。在 constructor 方法中,我们必须声明 “power” 参数并且使用super函数,来表示属性是在父元素中声明的。

当我们实例化新的对象的时候,其实我们传入了声明在 constructor 函数里的参数。哒哒!我们就可以在实例中访问在父类中声明的属性和方法了。
// 祖>>>>子 继承
class Character{
    constructor(speed){
        this.speed=speed;
    }
    move=()=>console.log(`i'm moving at this speed of ${this.speed}`)
}
class Enemy extends Character{
    constructor(power,speed){
        super(speed);
        this.power=power
    }
    attack=()=>console.log(`i'm attacking with a power of ${this.power}`)
}
class Alien extends Enemy{
    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=new Alien('Ali','i am ali this alien!',10,50)
alien1.move();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值