Where to declare class constants?

后端 未结 9 1465
悲&欢浪女
悲&欢浪女 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:52

    You must make your constants like you said :

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

    And you access like that :

    Foo.CONSTANT1;
    

    or

    anInstanceOfFoo.__proto__.constructor.CONSTANT1;
    

    All other solutions alloc an other part of memory when you create an other object, so it's not a constant. You should not do that :

    Foo.prototype.CONSTANT1 = 1;
    

提交回复
热议问题