Correctly declare static variables in JavaScript c

2020-04-08 05:45发布

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.

2条回答
够拽才男人
2楼-- · 2020-04-08 06:27

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.

查看更多
何必那么认真
3楼-- · 2020-04-08 06:35

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.

查看更多
登录 后发表回答