Static Methods in ES6

Static methods, like many other features introduced in ES6, are meant to provide class-specific methods for object-oriented programming in Javascript. Static methods in Javascript are similar to class methods in Ruby. To declare a static method, simply prefix a method declaration with the word static inside the class declaration.

class Foo(){ static methodName(){ console.log(“bar”) }}

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.

Since these methods operate on the class instead of instances of the class, they are called on the class. 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

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.

With the introduction of classes in ES6, we can now utilize prototype-based inheritance, super calls, constructors, instance and static methods, which make interoperability much easier. Say we have a subclass to a parent class, any static methods that we declared are available to the subclasses as well. This was not available in ES5 unless the methods are explicitly copied over.

Static Getter

Getter and setter accessors were introduced in ES5, and can be used with the static keyword.

class User{ constructor(name){ = name } static get Leader(){ return new User(wat) }}

Note that static properties are a separate concept from static methods, and are still under development. The rationale for having static properties is best explained here:

Currently it?s possible to express static methods on a class definition, but it is not possible to declaratively express static properties. As a result people generally have to assign static properties on a class after the class declaration ? which makes it very easy to miss the assignment as it does not appear as part of the definition.



es-class-public-fields – Stage 1 proposal for declarative class properties in ES


The static keyword defines a static method for a class.

15. Classes

A class and a subclass: Using the classes: Under the hood, ES6 classes are not something that is radically new: They?

No Responses

Write a response