js 类静态方法引用 self(如 php 中的 self)

Chr*_*ris 7 javascript typescript

有没有一种方法可以引用包含静态方法的类,而无需再次显式指定该类。所以代替这个:

class User {
    static welcome = 'Hello'

    static greet() {
        console.log(User.welcome)
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样的东西:

class User {
    static welcome = 'Hello'

    static greet() {
        console.log(self.welcome)
    }
}
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 6

类只不过是一个函数对象。静态方法只不过是该对象的函数属性。每当您调用 时obj.method()this都会引用该函数内的对象。

因此,如果您调用 with 方法User.greet()this将引用该函数对象User

class User {
  static get welcome() {
    return 'hello';
  }

  static greet() {
    console.log(this.welcome)
  }
}

User.greet();
Run Code Online (Sandbox Code Playgroud)


在实例方法内部,您可以通过 引用该类this.constructor