How can I refer to a class from a static method without using the class name itself in JavaScript (similar to PHP\'s self
and self::method_name
)?<
If all of those methods are static then you can use this
.
class FooBar {
static foo() {
return 'foo';
}
static bar() {
return 'bar';
}
static foobar() {
return this.foo() + this.bar();
}
}
Yes: the syntax you're asking about is "this".
From MDN:
https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1
As MDN describes it, “Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.” In other words, static methods have no access to data stored in specific objects. ...
Note that for static methods, the
this
keyword references the class. You can call a static method from another static method within the same class with this.
Also note:
There are two ways to call static methods:
Foo.methodName() // calling it explicitly on the Class name // this would give you the actual static value. this.constructor.methodName() // calling it on the constructor property of the class // this might change since it refers to the class of the current instance, where the static property could be overridden
You can use the this keyword to refer to the object itself.
See example below:
class FooBar {
static foo() {
return 'foo';
}
static bar() {
return 'bar';
}
static foobar() {
return this.foo() + this.bar();
// self::foo() + self::bar() would have been more desirable.
}
}
const res = FooBar.foobar();
console.log(res);