Super方法

Super方法用来调用和访问父类的方法

super 关键词可以单独出现在子类的构造函数中,调用父类的构造函数为子类属性赋值(注意super关键词必须出现在this关键词之前)。

class Father{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.name = 'Father'
    }
    sayName(){
        console.log(this.name)
    }
}
class Child extends Father{
    constructor(x, y){
        super(x, y);
        this.name = 'Child';
    }
    sayPosition(){
        console.log(`x:${this.x},y:${this.y}`);
    }
}
new Child(5,10).sayPosition(); // x:5,y:10

super 方法还可以调用父类的函数

class Father{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.name = 'Father'
    }
    sayName(){
        console.log(this.name)
    }
}
class Child extends Father{
    constructor(x, y){
        super(x, y);
        this.name = 'Child';
    }
    sayName(){
        super.sayName();
    }
}
new Child().sayName(); // Child

super 只能访问父类的方法,不能直接访问属性,访问属性需要使用 super.constructor.Property

class Father{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.name = 'Father'
    }
}
class Child extends Father{
    constructor(x, y){
        super(x, y);
        this.name = 'Child';
    }
    test(){
        console.log(super.name,super.constructor.name); // 试试是否能访问父类的属性
    }
}
new Child().test(); // undefined,"Father"

我们知道在类中访问自身的静态方法分为两种

1.在一个静态方法中直接使用 this.staticMethod来访问另一个静态方法

2.在非静态方法中使用 CLASS.staticMethod或者是this.constructor.staticMethod来访问静态方法

class Father{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.name = 'Father'
    }
    static ping(){
        return 'ping';
    }
    static bing(){
        // 静态方法中直接使用 this.staticMethod 来访问
        console.log(`bing,${this.ping()}`);
    }
    unStatic(){
        // 非静态方法中使用 this.constructor.staticMethod 来访问
        console.log(this.constructor.ping());
    }
}
Father.bing(); // bing,ping
new Father().unStatic();// ping

在子类中访问父类的静态方法与此类似,

1.在子类静态方法中访问父类静态方法 super.FatherStaticMethod

2.在子类非静态方法中访问父类静态方法 super.constructor.FatherStaticMethod

当然,无论什么时候,使用Father.staticMethod来访问静态方法都是可以的。

class Father{
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.name = 'Father'
    }
    static ping(){
        return 'ping';
    }
}
class Child extends Father{
    constructor(x, y){
        super(x, y);
        this.name = 'Child';
    }
    sayName(){
        // 在子类的非静态方法中访问父类静态方法
        console.log(super.constructor.ping());
    }
    static bing(){
        // 在子类的静态方法中访问父类静态方法
        console.log(`bing,${super.ping()}`);
    }
}
new Child().sayName(); // ping
Child.bing(); // bing,ping
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值