Where to declare class constants?

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

    Also with namespaces

    var Constants = {
        Const1: function () {
            Const1.prototype.CONSTANT1 = 1;
            Const1.prototype.CONSTANT2 = 2;
        },
    
        Const2: function () {
            Const2.prototype.CONSTANT3 = 4;
            Const2.prototype.CONSTANT4 = 3;
        }
    };
    
    0 讨论(0)
  • 2021-02-18 14:56

    If you're using jQuery, you can use $.extend function to categorize everything.

    var MyClass = $.extend(function() {
            $.extend(this, {
                parameter: 'param',
                func: function() {
                    console.log(this.parameter);
                }
            });
            // some code to do at construction time
        }, {
            CONST: 'const'
        }
    );
    var a = new MyClass();
    var b = new MyClass();
    b.parameter = MyClass.CONST;
    a.func();       // console: param
    b.func();       // console: const
    
    0 讨论(0)
  • 2021-02-18 15:01

    what you are doing is fine (assuming you realize that your example is just setting the same property twice); it is the equivalent of a static variable in Java (as close as you can get, at least without doing a lot of work). Also, its not entirely global, since its on the constructor function, it is effectively namespaced to your 'class'.

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