Correctly declare static variables in JavaScript classes

前端 未结 2 1560
孤街浪徒
孤街浪徒 2021-01-19 13:37

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

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

    static async open() {
        await $.get(         


        
相关标签:
2条回答
  • 2021-01-19 14:08

    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.

    0 讨论(0)
  • 2021-01-19 14:11

    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.

    0 讨论(0)
提交回复
热议问题