Where to declare class constants?

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

    All you're doing in your code is adding a property named CONSTANT with the value 1 to the Function object named Foo, then overwriting it immediately with the value 2.

    I'm not too familiar with other languages, but I don't believe javascript is able to do what you seem to be attempting.

    None of the properties you're adding to Foo will ever execute. They're just stored in that namespace.

    Maybe you wanted to prototype some property onto Foo?

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

    Not quite what you're after though.

提交回复
热议问题