JavaScript类语法:静态数据成员

4

我找不到关于如何使用(相对较新的)类语法在JavaScript中定义静态数据成员的任何信息。这个是否可能?请看下面的示例代码:

class Foo {
  constructor() {
    this.name = 'Default Name for each Instance';
    // staticData1 = 'Static Data 1'; // syntax error
    let staticData2 = 'Static Data 2'; // undefined outside
  }

  doSthSpecial() {
    console.log('Executing a method from instance "' + this.name + '"');
  }

  static doSthStatic() {
    console.log('Executing a method that does the same for each instance of "Foo"');
  }
}

foo = new Foo();
console.log(foo.name);
foo.doSthSpecial();
Foo.doSthStatic();
// The problematic case:
console.log(Foo.staticData2);

这是一个第二阶段的提案,对吧?所以它还没有标准化。我正在使用babel.js来解决这个问题。编辑:@shaochuancs解释得很好。 :) - Con Antonakos
5个回答

4

好的,首先,这很遗憾,因为无法在(匿名)类表达式中完成,例如 return class { /*...*/ } ,否则这些是非常好的。第二点:太棒了,我期待未来版本的标准。 - Chris K
实际上,如果您使用Babel转换ES6/ES7代码,则可以立即使用静态字段的第二阶段提案语法。 - shaochuancs

4

我发现一个解决方法,可以接近所要求的功能。可以使用“计算属性”(即“get方法”)并将其设为静态。然后就不需要使用“()”函数/方法调用语法,而且它可以在没有类实例的情况下使用。虽然可能会稍微低效一些。 示例:

let Foo = class {
  static get staticData() {
    return 'Static Data';
  }
}

console.log(Foo.staticData);

3
这样做的好处是,可以将复杂的细节保留在类内部,同时也能使代码更加通俗易懂。
class cExample
{  
  static init_index() {
     cExample.index = 0;
  }   

  static get_index() {
     return ++cExample.index;
  }   
}

cExample.init_index();

example = new cExample();
console.log(cExample.get_index());  // 1
example = new cExample();
console.log(cExample.get_index());  // 2
example = new cExample();
console.log(cExample.get_index());  // 3

2

另一个解决方法是在ES7之前,将静态成员放在类后面,虽然不太优雅,但至少可以起到作用。

class Field {

  constructor(index) {
    this.index = index;
  }

  getName(name) {
    return this.name;
  }
}

Field.DISPLAY_AS_TEXT = 2001;
Field.DISPLAY_AS_BARCODE = 2002;


1
您可以在构造函数中初始化静态变量:
class Foo {
  constructor () {
    if (Foo.myStatic === undefined) Foo.myStatic = 'XXX';
    // or if appropriate
    Foo.myStatic = Foo.myStatic || 'XXX';
    // or the ES2020
    Foo.myStatic = Foo.myStatic ?? 'XXX';
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接