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

2024-02-25

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'

如上所示,我可以轻松地从实例获取子类名称。不太确定如何从静态方法访问。

实施思路static get callingClassType()欢迎。


callingClassType是一个函数(在本例中是一个 getter,同样的事情)。的价值this函数内部取决于它的调用方式。如果你调用一个函数foo.bar(), then this inside bar将参考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)

看一看访问 MDN 文档以了解更多信息this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐