gpt4 book ai didi

JavaScript ES6 : How to retrieve calling subclass from a static method defined in superclass

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:33 25 4
gpt4 key购买 nike

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 将引用 SubClassSubClass 本身是一个(构造函数)函数,因此您可以通过 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)

看看at the MDN documentation to learn more about this .

关于JavaScript ES6 : How to retrieve calling subclass from a static method defined in superclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44093052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com