ES6静态方法指的是自我? [英] ES6 Static method referring to self?

查看:68
本文介绍了ES6静态方法指的是自我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个班级.存储库和UserRepository.我想在存储库中定义一个静态方法,该方法在运行时在UserRepository中调用一个静态函数.有什么干净的方法可以做到这一点吗?

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.

我的问题是,如何从基类中引用子类方法model()?

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

推荐答案

现在有意义的是,上面的代码不起作用,因为它可能是引用一个实例,在这种情况下,我没有任何实例.

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.

不,this将如何引用一个实例,因为您说自己没有实例?

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

不,静态方法也像其他任何方法一样是函数,并且this引用它们在其上被调用的任何内容.在UserRepository.printModel();中,this将引用UserRepository.而且,您可以只使用this.model()调用该类的静态.model()方法.

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.

这篇关于ES6静态方法指的是自我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆