This question already has an answer here:
- ES6 - Call static method within a class 3 answers
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?
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. InUserRepository.printModel();
,this
will refer toUserRepository
. And you can just usethis.model()
to call the static.model()
method of that class.