获取已调用静态函数的类的名称

Kof*_*lin 3 javascript

所以我的问题如下:我可以获得调用函数的类的名称吗?为了说明这个问题,我将给出一个简短的代码示例。

class Base {
    static getClassName() {
        // get the caller class here
    }
}

class Extended extends Base { }

Base.getClassName(); // Base
Extended.getClassName(); // Extended
Run Code Online (Sandbox Code Playgroud)

谁能告诉我如何做到这一点,或者说这是否可能。

Gui*_*ury 6

以下代码应该可以工作:

class Base {
  static getClassName() {
    return this.name;
  }
}

class Extended extends Base {}

console.log(Base.getClassName()); // Base
console.log(Extended.getClassName()); // Extended
Run Code Online (Sandbox Code Playgroud)

在静态方法中,this指的是类对象本身。