I have this class which does an internal call to a static method:
export class GeneralHelper extends BaseHelper{ static is(env){ return config.get('env:name') === env; } static isProd(){ return GeneralHelper.is('prod'); } }
Are there any keywords I can use to replace the class name in the line below:
GeneralHelper.is('prod');
In PHP there are self
, static
etc. Does ES6 provide anything similar to these?
TY.
To call them we need to create the object of the class in which it is defined. The static method gets a call in two ways one using this keyword another from the constructor. Static methods cannot directly call the nonstatic method. On-static methods use instance variable state to affect their behavior.
@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .
JavaScript static methods belong to the class, not to the instance of the class. So JavaScript static methods are not called on the instance of the class they are made to call directly on the class.
No, a static method cannot call a non-static method.
If you are calling the static function from inside an instance, the right way to refer to the static function of the class is:
this.constructor.functionName();
Call static methods from regular ES6 class methods
It's the same as calling a method on an ordinary object. If you call the GeneralHelper.isProd()
method, the GeneralHelper
will be available as this
in the method, so you can use
class GeneralHelper { static is(env) { … } static isProd(){ return this.is('prod'); } }
This will however not work when the method is passed around as a callback function, just as usual. Also, it might be different from accessing GeneralHelper
explicitly when someone inherits isProd
from your class and overwrites is
, InheritedHelper.isProd()
will produce other results.
If you're looking to call static methods from instance methods, see here. Also notice that a class which only defines static methods is an oddball, you may want to use a plain object instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With