如何在不使用其名称的情况下从 class 中访问 class 本身

How to access the class itself from within a class without using its name

是否可以在 classes 函数中访问 class 本身:

class MyClass {
  static get myFunction() { return "foo"; }
  
  constructor() {
    console.log(MyClass.myFunction); // "foo" -- it works when using its name. This is what we want but without using the name
    console.log(this.myFunction); //undefined
    console.log(this.prototype.myFunction); //Cannot read property 'myFunction' of undefined
  }

}

new MyClass();

是否可以实现与使用 MyClass.myFunction() 相同的效果并访问 static 方法而不使用 class 的名称(在这种情况下不使用 MyClass 在这个例子中?

有点像this.master.myFunction()(我只是在master上面做的,显然不叫master)

JSBin: https://jsbin.com/hawituxosu/1/edit?js,console

这可能吗?谢谢!

您可以在此处执行的一个选项是在实例方法中调用静态方法并调用该实例方法

class MyClass {
  static get myFunction() { return "foo"; }

  constructor() {
    console.log(MyClass.myFunction); // "foo" -- whith using its name it works. This is what we want but without using the name
    console.log(this.constructor.myFunction);
  }
  myFunction2() {
     return this.constructor.myFunction();
  }
}
const master = new MyClass();
master.myFunction2();
   this.constructor.myFoo

构造函数属性在这里帮助你

你可以用 constructor 做这个

Returns a reference to the Object constructor function that created the instance object

构造函数属性具有三个目的:

1.获取class对象。

2. 创建新实例

3.调用超级构造函数

class MyClass {
  static get myFunction() { return "foo"; }

  constructor() {
    console.log(this.constructor.myFunction); 
  }

}

new MyClass();

您可以使用以下方式绕过 class 名称:

this.__proto__.constructor.name   // MyClass

class MyClass {
  static get myFunction() { return "foo"; }

  constructor() {
    
    console.log(eval(this.__proto__.constructor.name + ".myFunction"));  //foo
  }

}

new MyClass();