ES6 Static method referring to self? [duplicate]

2019-07-03 15:21发布

问题:

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?

回答1:

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.