Javascript ES6:如何从超类中定义的静态方法检索调用子类

Javascript ES6:如何从超类中定义的静态方法检索调用子类,javascript,es6-class,Javascript,Es6 Class,JavaScript的新特性 寻求有关如何使用ES6类从超类中定义的静态方法访问调用类名的指导。我花了一个小时寻找,但没有找到解决办法 一段代码片段可能有助于澄清我在寻找什么 class SuperClass { get callingInstanceType() { return this.constructor.name } static get callingClassType() { return '....help here ...' } } class SubCla

JavaScript的新特性

寻求有关如何使用ES6类从超类中定义的静态方法访问调用类名的指导。我花了一个小时寻找,但没有找到解决办法

一段代码片段可能有助于澄清我在寻找什么

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'
如上所示,我可以很容易地从实例中获取子类名称。不太确定如何从静态方法访问


欢迎使用
超类.prototype.constructor.name
实现
静态get callingClassType()
的想法。

使用
超类.prototype.constructor.name

类超类{
获取callingInstanceType(){返回this.constructor.name}
静态get callingClassType(){return SuperClass.prototype.constructor.name;}
}
类子类扩展超类{}
类子类2扩展了超类{
静态get callingClassType(){返回子类2.prototype.constructor.name;}
}
console.log(超类.callingClassType);/'超类
console.log(SubClass.callingClassType);/'超类

console.log(子类2.callingClassType);/'子类2'
调用classtype
是一个函数(在本例中是一个getter,也是一个函数)。函数中
this
的值取决于调用方式。如果使用
foo.bar()
调用函数,则
内的
bar
将引用
foo

因此,如果您使用
子类.callingClassType
来“调用”函数,
将引用
子类
SubClass
本身就是一个(构造函数)函数,因此可以通过
name
属性获取其名称

因此,您的方法定义应该是

static get callingClassType() { return this.name; }
类超类{
获取callingInstanceType(){
返回this.constructor.name
}
静态get callingClassType(){
返回此名称
}
}
类子类扩展超类{}
设sc=新的子类()
console.log(sc.callingInstanceType)

log(SubClass.callingClassType)
您将很难找到用任何语言实现这一点的方法。因为static方法没有这个意思,所以没有“调用实例”的概念
@Derek,返回
函数
,而不是
子类
。有没有办法检查呼叫链并从中拔出?@Kevin我知道没有呼叫实例。我想知道是否有什么方法可以检查链条。@Kevin实际上用PHP很容易:。正如下面Felix的回答所示,它在JS中也是可行的。谢谢@Derek。但是我想要
子类。调用classtype
返回
子类
,非
超类
您必须在
子类
中重新定义函数才能获得该值,因为该函数不在
子类
的原型上,除非您添加它。我添加了一个示例
子类2
,它重新定义了该方法。非常感谢。当你知道怎么做的时候很简单。