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

时间:2018-11-21 11:19:14

标签: javascript ecmascript-6 es6-class

是否可以在类函数内部访问class本身:

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.myFunction); //undefined
    console.log(this.prototype.myFunction); //Cannot read property 'myFunction' of undefined
  }

}

new MyClass();

是否可以实现与使用MyClass.myFunction()相同的方式并访问static方法而无需使用类名(在本例中,无需使用MyClass)?

类似this.master.myFunction()的东西(我只是在这里master的名字,显然不是大师)

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

那有可能吗?谢谢!

4 个答案:

答案 0 :(得分:2)

您可以在此处执行的一种选择是在实例方法内部调用静态方法,然后调用该实例方法

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();

答案 1 :(得分:2)

您可以为此使用constructor

  

返回对创建实例对象的Object构造函数的引用

构造函数属性具有三个用途:

1。。获取类对象。

2。。创建一个新实例

3。调用超级构造函数

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

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

}

new MyClass();

答案 2 :(得分:1)

   this.constructor.myFoo

构造函数属性可以在这里帮助您

答案 3 :(得分:1)

您可以使用以下方法解决班级名称的问题:

this.__proto__.constructor.name   // MyClass

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

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

}

new MyClass();