Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly declare static variables in JavaScript classes

In my code, I do the following (very simplified):

class AddOrSelectAddress {
    static body; // <-- Error

    static async open() {
        await $.get(basePath + 'Manage/AddOrSelectAddress', null, result => {
            this.body = document.createElement('div');
            this.body.innerHTML = result;
        });
        // ...
    }

    static someOtherMethod() {
        // do something with body
    }
}

My code works fine in Chrome. Firefox, though, complaints an error in the second line of code:

SyntaxError: bad method definition

I'm relatively new to class-based JavaScript programming. What am I doing wrong here?

Static variables in JavaScript doesn't really help me, because it mainly uses old syntax.

like image 743
André Reichelt Avatar asked Mar 03 '23 07:03

André Reichelt


2 Answers

Static class fields are a stage 3 proposal, meaning they're not yet an official part of the JavaScript language. (Stage 4 is the final stage.) You can read more about the proposal here and the proposal process here.

Currently, Chrome (as of version 72) is the only browser that supports static class fields.

To use this feature in other browsers you would need to use Babel with @babel/plugin-proposal-class-properties to transpile your code. If you're not already using Babel, however, this might be overkill.

Alternatively, you can assign a property to the class after initializing it. This isn't semantically identical, but works for your (and, indeed, most) use cases.

class AddOrSelectAddress {
  // ...
}

AddOrSelectAddress.body = 'some initial value';

You can see this working in the below snippet.

class AddOrSelectAddress {
  static changeBody(val) {
    this.body = val;
  }

  static someMethod() {
    console.log('in someMethod body is', this.body);
  }

  static someOtherMethod() {
    console.log('in someOtherMethod body is', this.body);
  }
}
AddOrSelectAddress.body = 'some initial value';

AddOrSelectAddress.someMethod();
AddOrSelectAddress.changeBody('some other value');
AddOrSelectAddress.someOtherMethod();

If you don't want to set an initial value for body then you could just omit the line (since accessing a nonexistent property of an object returns undefined), or you could explicitly set it to undefined.

like image 106
Jordan Running Avatar answered Mar 07 '23 20:03

Jordan Running


Static methods are perfectly fine to use. However static properties are a recent addition that dont work in all browsers yet. It works in Chrome but like you said not in firefox. Please take a look at this article as it backs up my answer : https://javascript.info/static-properties-methods. To fix your issue you could declare the variable inside your static method.

like image 38
Kevin.a Avatar answered Mar 07 '23 19:03

Kevin.a