Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

javascript - Purpose of Static Methods in ECMAScript 6 Classes

What sort of issues with ES5 are static class methods in ES6 supposed to deal with?

The Babel documentation has the following example in its section regarding ES6 classes, though it does not actually state what this pattern accomplishes.

Classes support prototype-based inheritance, super calls, instance 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();
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

So, this ES6 ES2015 code:

class A {
   static doStuff() {}
}

...equals (in ES5):

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

Why you need static functions? Well, transpiled code won't support statics at all, since even functions are objects and static functions are turned into own properties of constructor function.

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

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

var instance = A.create();

Anyway, static member usage is a very diffuse topic and it goes out of scope of an objective answer. It has a lot of use cases and these are universal to any programming language.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...