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