daalgi
daalgi

Reputation: 169

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? 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

Answers (1)

Jonas Wilms
Jonas Wilms

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

Related Questions