Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 - Call static method within a class

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.

like image 822
Shlomi Avatar asked Jun 29 '15 12:06

Shlomi


People also ask

How do you call a static method in JavaScript?

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.

Can I call a static method inside a regular one?

@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:: .

Can you call a static method from an instance JS?

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.

Can we call static method from non-static method JavaScript?

No, a static method cannot call a non-static method.


2 Answers

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

like image 53
Otto Nascarella Avatar answered Sep 22 '22 10:09

Otto Nascarella


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.

like image 25
Bergi Avatar answered Sep 20 '22 10:09

Bergi