Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Class Syntax: Static Data Members

I cannot find any information about how one defines static data members in JavaScript using the (relatively new) class syntax. Is it even possible? Please see the following example code:

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);
like image 400
Chris K Avatar asked Sep 19 '25 02:09

Chris K


2 Answers

You can use Foo.staticData2 = 'Static Data 2' to define static data member of class Foo, after Foo itself is defined.

According to ES6, there is no static property inside class definition, only static method.

In ES7, there is a proposal on static field definition, currently it is at stage 2 (https://github.com/tc39/proposal-class-public-fields). Good new is: Babel has supported this proposal (https://babeljs.io/docs/plugins/transform-class-properties/).

like image 162
shaochuancs Avatar answered Sep 20 '25 15:09

shaochuancs


I found a work-around that comes quite close to what is asked. One can use a computed property ("get method") and make it static. Then there is no need for the "()" function/method call syntax and it is available without any instance of the class. May be a little less efficient though. Example:

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

console.log(Foo.staticData);
like image 26
Chris K Avatar answered Sep 20 '25 14:09

Chris K