简体   繁体   English

Javascript子类中的实例方法可以将其称为父方法静态方法吗?

[英]Can a instance method in a Javascript subclass call it's parents static method?

This doesn't work. 这行不通。 Is there a way for a child class in JS to have access to its parents static methods? JS中的子类是否可以访问其父类的静态方法?

class Person {
    constructor() {}

    static isHuman() {
        return 'yes I am';
    }
}


class Brian extends Person {
    constructor() {
        super();
    }

    greeting() {
        console.log(super.isHuman())
    }
}

const b = new Brian();
b.greeting();

For static methods, use the class name rather than super. 对于静态方法,请使用类名称,而不要使用super。

 class Person { constructor() {} static isHuman() { return 'yes I am'; } } class Brian extends Person { constructor() { super(); } greeting() { console.log(Person.isHuman()) } } const b = new Brian(); b.greeting(); 

Yes you can. 是的你可以。 You can use super but to get at the static method you have to access the constructor property of it: 您可以使用super但要获取静态方法,您必须访问它的构造方法属性:

super.constructor.isHuman()

You can also use the class name directly: 您也可以直接使用类名:

Person.isHuman();
//this works because Brian inherits the static methods from Person
Brian.isHuman();

Or by going up the prototype chain 或通过上链原型链

//would be referencing Brian
this.constructor.isHuman();
//would be referencing Person
this.__proto__.constructor.isHuman();
Object.getPrototypeOf(this).constructor.isHuman();

Demo 演示

 class Person { constructor() {} static isHuman() { return 'yes I am'; } } class Brian extends Person { constructor() { super(); } greeting() { console.log("From super: ", super.constructor.isHuman()) console.log("From class name (Brian): ", Brian.isHuman()) console.log("From class name (Person): ", Person.isHuman()) console.log("From prototype chain: ", this.constructor.isHuman()) console.log("From prototype chain: ", Object.getPrototypeOf(this).constructor.isHuman()) } } const b = new Brian(); b.greeting(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM