Where to declare class constants?

后端 未结 9 1397
悲&欢浪女
悲&欢浪女 2021-02-18 14:26

I\'m using class members to hold constants. E.g.:

function Foo() {
}

Foo.CONSTANT1 = 1;
Foo.CONSTANT2 = 2;

This works fine, except that it see

9条回答
  •  时光说笑
    2021-02-18 14:44

    First, I recommend moving your class declaration inside of an IIFE. This cleans up the code, making it more self-contained, and allows you to use local variables without polluting the global namespace. Your code becomes:

    var Foo = (function() {
      function Foo() {
      }
    
      Foo.CONSTANT1 = 1;
      Foo.CONSTANT2 = 2;
    
      return Foo;
    })();
    

    The problem with assigning constants directly to the class as attributes is that those are writable. See this snippet:

    var output = document.getElementById("output");
    
    var Foo = (function() {
      function Foo() {
      }
    
      Foo.CONSTANT1 = 1;
      Foo.CONSTANT2 = 2;
    
      return Foo;
    })();
    
    Foo.CONSTANT1 = "I'm not very constant";
    
    output.innerHTML = Foo.CONSTANT1;

    The best solution I have found is to define read-only properties for accessing the constants outside of the class.

    var output = document.getElementById("output");
    
    var Foo = (function() {
      const CONSTANT1 = "I'm very constant";
    
      function Foo() {
      }
    
      Object.defineProperty(Foo, "CONSTANT1", {
        get: function() {
          return CONSTANT1;
        },
      });
    
      return Foo;
    })();
    
    Foo.CONSTANT1 = "some other value";
    
    output.innerHTML = Foo.CONSTANT1;

    (Technically you could ditch the const CONSTANT1 statement and just return the value from the property definition, but I prefer this because it makes it easier to see all the constants at a glance.)

提交回复
热议问题