[英]Access to property defined in child class from static method in the parent class - javascript
Is there a way to have a parent class with static methods that call a property defined in the child class in javascript?有没有一种方法可以让父类具有调用 javascript 子类中定义的属性的静态方法? The code idea would be something like this:
代码思路是这样的:
class Base {
static greet() {
return `Hi ${username}!`
}
}
class ChildClass extends Base {
username = "Jim"
}
ChildClass.greet()
You can access properties of the class (also inherited ones) via this
, and you can set properties of the subclass just the way you do with every other object:您可以通过
this
访问类的属性(也可以是继承的属性),并且可以像处理其他所有对象一样设置子类的属性:
class Base {
static greet() {
return `Hi ${this.otherName}!`; // << you need this. here
}
}
class Child extends Base { }
Child.otherName = "Jim"; // << there are no static properties yet, we have to replicate that behaviour
name
is a bad property name, as it clashes with the internal function.name
... name
是一个错误的属性名称,因为它与内部function.name
冲突。name ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.