作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
JavaScript 新手。
寻求有关如何从使用 ES6 类的父类(super class)中定义的静态方法 访问调用类名称的指导。我花了一个小时进行搜索,但未能找到解决方案。
一段代码可能有助于阐明我在寻找什么
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'
如上所示,我可以轻松地从实例中获取子类名称。不太确定如何从静态方法访问。
欢迎提出static get callingClassType()
的实现想法。
最佳答案
callingClassType
是一个函数(好吧,在这种情况下是一个 getter,同样的事情)。函数内 this
的值取决于它的调用方式。如果您使用 foo.bar()
调用函数,则 bar
内的 this
将引用 foo
。
因此,如果您使用 SubClass.callingClassType
“调用”函数,this
将引用 SubClass
。 SubClass
本身是一个(构造函数)函数,因此您可以通过 name
属性获取它的名称。
所以你的方法定义应该是
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)
关于JavaScript ES6 : How to retrieve calling subclass from a static method defined in superclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093052/
我是一名优秀的程序员,十分优秀!