这不起作用。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();
是的你可以。您可以使用super
但要获得静态方法,您必须访问它的构造函数属性:
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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句