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

时间:2018-11-11 00:56:53

标签: javascript

这不起作用。 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();

2 个答案:

答案 0 :(得分:0)

对于静态方法,请使用类名而不是超级类。

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();

答案 1 :(得分:0)

可以。您可以使用super,但是要使用静态方法,您必须访问它的Constructor属性:

super.constructor.isHuman()

您也可以直接使用类名:

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

或者通过上链原型

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

演示

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();