'js class static method refer to self (like self in php)

Is there a way to refer to the class that a static method is included in without explicitly specifiying the class again. So instead of this:

class User {
    static welcome = 'Hello'

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

Something like this:

class User {
    static welcome = 'Hello'

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


Solution 1:[1]

A class is nothing but a function object. Static methods are nothing but function properties on that object. Whenever you call obj.method(), this refers to the object inside that function.

So if you call the method with User.greet(), this will refer to the function object User.

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

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

User.greet();

Inside instance methods you can refer to the class via this.constructor.

Solution 2:[2]

You can allways use "this":

class User {
  static welcome = 'Hello';

  static greet() {
        alert(this.welcome)
  }
}

User.greet();

But in case of static methods it will refer to type itself.

Here is what specs says about value of "this":

When the root declaration is an instance member or constructor of a class, the ThisType references the this-type of that class.

When the root declaration is a member of an interface type, the ThisType references the this-type of that interface.

Solution 3:[3]

Sadly, there is no such thing as self in JS, since this in JS is basically already a "merge" of this and self as described in other answers.

If you don't like to do this for a static call, you can actually do pretty similar thing as in PHP.

TL;DR Refer to the class by its name e.g. MyClass.myMethod()

class A {
    static one () { console.log("I am one"); }
    static two () { A.one(); }
}
A.one(); // Outputs/Logs: "I am one"

PHP equivalent could be something like

<?php
class A {
    public static function one() { echo "I am one"; }
    public static function two() { A::one(); }
}

A::two(); // Outputs: "I am one"

Bonus info: In JS, you can even do static two = () => A.one();, which is not available with arrow functions in PHP since in class static variable implies constant expression.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 jave.web