3

I have two classe; Repository and UserRepository. I want to define a static method in Repository that at runtime calls a static function in UserRepository. Is there any clean way to do this?

class Repository {
    static printModel() {
        return console.log(this.constructor.model())
    }
}

class UserRepository extends Repository {
    static model() {
        return "I am a user";
    }
}

UserRepository.printModel(); // Doesn't work; want it to print "I am a user"

Now it makes sense that the above doesn't work, as this probably referes to an instance, and I have no instances in this case.

My question is, how do I refer to the subclass method model() from the baseclass?

Poyan
  • 6,243
  • 6
  • 28
  • 30
  • 2
    Just tested it and `this.model();` seems to do the trick. Did you try that? –  Dec 02 '15 at 20:23

1 Answers1

2

Now it makes sense that the above doesn't work, as this probably referes to an instance, and I have no instances in this case.

No, how would this refer to an instance, as you say you don't have any?

No, static methods are just functions like any other methods as well, and this refers to whatever they were invoked on. In UserRepository.printModel();, this will refer to UserRepository. And you can just use this.model() to call the static .model() method of that class.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375