检测 ES6 中的静态超级方法 class

Detect static super method in ES6 class

我有一个基地class和一个子基地class。我希望我的 class 类型有一个通过字符串标识它的静态方法。 (所以我可以在对象中查找某种类型的处理程序。我可以直接将 class 粘贴到其中,但将 class 的整个源代码转换为字符串并将其用作关键,这似乎不是最理想的。)

我需要:

这是我想象的代码编写方式,但是 super.id 未定义,因此 if 总是失败。检查 if (super) {} 也因语法错误而失败,super.id() 失败,因为它是 "not a function".

class Y {
  static id() {
    if (super.id) {
      return `${super.id()}-${this.name}`;
    }
    else {
      return this.name;
    }
  }
}

class YY extends Y {}

// Outputs "Y YY", but I want "Y Y-YY"
console.log(Y.id(), YY.id()) 

我可以在 YY 中定义一个 static id() {} 方法,但是我必须在我的所有子 class 中手动执行它,这很容易出错。这样的事情可能吗?

您可以使用 Object.getPrototypeOf 而不是 super:

class Y {
  static id() {
    if (Object.getPrototypeOf(this).id) {
      return `${Object.getPrototypeOf(this).id()}-${this.name}`;
    }
    else {
      return this.name;
    }
  }
}

class YY extends Y {}

console.log(Y.id(), YY.id()) 

对于 super 它不起作用,因为它总是引用 Y class 的原型。但是 this 与您需要其原型的对象完全匹配,因此使用 Object.getPrototypeOf(this).id 您可以通过原型链获得很好的冒泡。