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

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

新 JavaScript。

寻求一些关于如何从 superclass 使用 ES6 classes。我已经花了一个小时搜索,但一直未能想出解决方案。

一段代码可能有助于阐明我正在寻找的内容

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'

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

欢迎提出实施 static get callingClassType() 的想法。

使用SuperClass.prototype.constructor.name:

class SuperClass {
    get callingInstanceType() { return this.constructor.name }
    static get callingClassType() { return SuperClass.prototype.constructor.name; }
}

class SubClass extends SuperClass {}
class SubClass2 extends SuperClass {
     static get callingClassType() { return SubClass2.prototype.constructor.name; }
}

console.log(SuperClass.callingClassType); // 'SuperClass'
console.log(SubClass.callingClassType); // 'SuperClass'
console.log(SubClass2.callingClassType); // 'SubClass2' 

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static#Examples

class Triple {
  static triple(n) {
    if (n === undefined) {
      n = 1;
    }
    return n * 3;
  }
}

class BiggerTriple extends Triple {
  static triple(n) {
    return super.triple(n) * super.triple(n);
  }
}

console.log(Triple.triple());        // 3
console.log(Triple.triple(6));       // 18

var tp = new Triple();

console.log(BiggerTriple.triple(3));
// 81 (not affected by parent's instantiation)

console.log(tp.triple());
// 'tp.triple is not a function'.

callingClassType 是一个函数(好吧,在这种情况下是 getter,同样的事情)。函数内部 this 的值取决于它的调用方式。如果您使用 foo.bar() 调用函数,则 bar 中的 this 将引用 foo.

因此,如果您 "call" 带有 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.