Javascript ES6:如何从超类中定义的静态方法中检索调用子类 [英] Javascript ES6: How to retrieve calling subclass from a static method defined in superclass

查看:113
本文介绍了Javascript ES6:如何从超类中定义的静态方法中检索调用子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript的新手。

New to JavaScript.

寻求有关如何从 静态方法 访问调用类名称的指导>使用ES6类在超类中定义。我花了一个小时进行搜索,但未能提出解决方案。

Seeking some guidance on how to access the calling class name from a static method defined in the superclass using ES6 classes. I've spent an hour searching, but have not been able to come up with a solution.

代码段可能有助于阐明我要查找的内容

A code snippet may help clarify what I am seeking

class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return '....help here ...' }
}

class SubClass extends SuperClass { }

let sc = new SubClass()

console.log(sc.callingInstanceType)     // correctly prints 'SubClass'
console.log(SubClass.callingClassType)  // hoping to print 'SubClass'

如上所述,我可以轻松地从实例获取子类名称。不太确定如何从静态方法访问。

As illustrated above, I can easily get the subclass name from a instance. Not quite sure how to access from a static method.

实现 static的想法,请获取callingClassType()

推荐答案

callingClassType 是一个函数(嗯,这是一个吸气剂情况相同)。函数内 this 的值取决于调用它的方式。如果您使用 foo.bar()调用函数,则 bar内的 this 将引用 foo

callingClassType is a function (well, a getter in this case, same thing). The value of this inside a function depends on how it is called. If you call a function with foo.bar(), then this inside bar will refer to foo.

因此,如果您用<$ c调用该函数$ c> SubClass.callingClassType ,将引用 SubClass SubClass 本身是一个(构造函数)函数,因此您可以通过 name 属性获取其名称。

Thus if you "call" the function with SubClass.callingClassType, this will refer to SubClass. SubClass is itself a (constructor) function thus you can get its name via the name property.

所以您的方法定义应该是

So your method definition should be

static get callingClassType() { return this.name; }

class SuperClass {
  get callingInstanceType() {
    return this.constructor.name
  }
  static get callingClassType() {
    return this.name
  }
}

class SubClass extends SuperClass {}

let sc = new SubClass()

console.log(sc.callingInstanceType)
console.log(SubClass.callingClassType)

有一个请查看MDN文档中的以了解有关<$ c $的更多信息c>此

Have a look at the MDN documentation to learn more about this.

这篇关于Javascript ES6:如何从超类中定义的静态方法中检索调用子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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