So *_* It 3 javascript es6-class
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'
Run Code Online (Sandbox Code Playgroud)
如上所示,我可以轻松地从实例中获取子类名称.不太确定如何从静态方法访问.
static get callingClassType()欢迎实施的想法.
callingClassType是一个函数(嗯,在这种情况下是一个吸气剂,同样的事情).值this函数内部取决于它是如何被调用.如果你用一个函数调用foo.bar(),那么this里面bar会引用foo.
因此,如果你"调用"函数SubClass.callingClassType,this将参考SubClass.SubClass它本身就是一个(构造函数)函数,因此您可以通过name属性获取其名称.
所以你的方法定义应该是
static get callingClassType() { return this.name; }
Run Code Online (Sandbox Code Playgroud)
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)Run Code Online (Sandbox Code Playgroud)