Reputation: 169
Is there a way to have a parent class with static methods that call a property defined in the child class in javascript? The code idea would be something like this:
class Base {
static greet() {
return `Hi ${username}!`
}
}
class ChildClass extends Base {
username = "Jim"
}
ChildClass.greet()
Upvotes: 3
Views: 1472
Reputation: 138247
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:
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
...
Upvotes: 4