Javascript ES6:如何从超类中定义的静态方法检索调用子类
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
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
,它重新定义了该方法。非常感谢。当你知道怎么做的时候很简单。