Assigning Static Methods in ECMAScript 6 Classes

What problems with ES5 are static class methods in ES6 that should be dealt with?

Babel documentation has the following example in its section regarding ES6 classes , although it isn't really stated what this template does.

Classes support prototype based inheritance, super calls, instances, and static methods and constructors

class SkinnedMesh extends THREE.Mesh {
  constructor(geometry, materials) {
    super(geometry, materials);

    this.idMatrix = SkinnedMesh.defaultMatrix();
    this.bones = [];
    this.boneMatrices = [];
    //...
  }
  update(camera) {
    //...
    super.update();
  }
  static defaultMatrix() {
    return new THREE.Matrix4();
  }
}

      

+3


source to share


2 answers


If you compile ES6 code with Babel and some class contains a static method, the code generated with ES5 will just add that static function to the constructor function.

So this <funny> ES6 ES2015 code:

class A {
   static doStuff() {}
}

      

... equals (in ES5):

function A() { }
A.doStuff = function() { };

      



Why do you need static functions? Well, the converted code will not support static at all, since even functions are objects, and static functions turn into native properties of the constructor function.

Static functions or properties can be used to implement the factory pattern:

class A {
   static create() {
      // Specific factory method code
   } 
}

var instance = A.create();

      

Anyway, using a static member is a very common topic and is beyond the scope of an objective answer. It has many use cases and is universal for any programming language.

+6


source


Consider a class containing only static methods:

class MyNamespace {
  static foo() { ... }
  static bar() { foo(); }
}

      

This is a pretty convenient way to organize your code entry in namespaces.



MyNamespace.foo();
MyNamespace.bar();

      

These are different than the standard static use cases in other OOP languages.

+1


source







All Articles