Where to declare class constants?

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

    You said your coming from Java - why don't you store that class in 1 file then and constants at the end of the file. This is what I use:

    filename: PopupWindow.js

    function PopupWindow() {
        //private class memebers
        var popup, lightbox;
        //public class memeber or method (it is the same in JS if I am right)
        this.myfuncOrmyMemeber = function() {};
    }
    
    //static variable
    PopupWindow._instance = null;
    //same thing again with constant-like name (you can't have "final" in JS if I am right, so it is not immutable constant but its close enough ;) - just remember not to set varibales with BIG_LETTERS :D)
    PopupWindow.MY_CONSTANT = 1;
    //yea, and same thing with static methods again
    PopupWindow._getInstance = function() {};
    

    So only difference is the position of static stuff. It is not nicly aligned inside class curly braces, but who cares, its always ctrl+click in IDE (or I use ctr+l to show all class methods - IntellijIdea can do that in JS dunno how about other IDEs) so your not gonna search it by your eye ;)

    Yea and I use _ before static method - it is not needed, I don't know why I started to do that :)

提交回复
热议问题