ECMAScript 6类中静态方法的目的 [英] Purpose of Static Methods in ECMAScript 6 Classes

查看:79
本文介绍了ECMAScript 6类中静态方法的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES5的哪些问题是ES6中应该处理的静态类方法?

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

Babel文档在关于ES6课程的部分,虽然它实际上没有说明这种模式的成就。

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();
  }
}


推荐答案

如果你用Babel编译ES6代码,有些类包含静态方法,ES5生成的代码只是将静态函数添加到构造函数中。

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.

所以,这个< strike> ES6 ES2015代码:

So, this ES6 ES2015 code:

class A {
   static doStuff() {}
}

...等于(在ES5中):

...equals (in ES5):

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

为什么需要静态功能? 以及,transiled代码根本不支持静态,因为即使函数是对象,静态函数也会转换为构造函数的自己的属性

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.

这篇关于ECMAScript 6类中静态方法的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆