Static Members

Adding additional methods directly onto constructors to simulate static members is another common pattern in ECMAScript 5 and earlier. For example:

  1. function PersonType(name) {
  2. this.name = name;
  3. }
  4. // static method
  5. PersonType.create = function(name) {
  6. return new PersonType(name);
  7. };
  8. // instance method
  9. PersonType.prototype.sayName = function() {
  10. console.log(this.name);
  11. };
  12. var person = PersonType.create("Nicholas");

In other programming languages, the factory method called PersonType.create() would be considered a static method, as it doesn’t depend on an instance of PersonType for its data. ECMAScript 6 classes simplify the creation of static members by using the formal static annotation before the method or accessor property name. For instance, here’s the class equivalent of the last example:

  1. class PersonClass {
  2. // equivalent of the PersonType constructor
  3. constructor(name) {
  4. this.name = name;
  5. }
  6. // equivalent of PersonType.prototype.sayName
  7. sayName() {
  8. console.log(this.name);
  9. }
  10. // equivalent of PersonType.create
  11. static create(name) {
  12. return new PersonClass(name);
  13. }
  14. }
  15. let person = PersonClass.create("Nicholas");

The PersonClass definition has a single static method called create(). The method syntax is the same used for sayName() except for the static keyword. You can use the static keyword on any method or accessor property definition within a class. The only restriction is that you can’t use static with the constructor method definition.

W> Static members are not accessible from instances. You must always access static members from the class directly.