I'm using class members to hold constants. E.g.:
function Foo() {
}
Foo.CONSTANT1 = 1;
Foo.CONSTANT2 = 2;
This works fine, except that it seems a bit unorganized, with all the code that is specific to Foo
laying around in global scope. So I thought about moving the constant declaration to inside the Foo()
declaration, but then wouldn't that code execute everytime Foo
is constructed?
I'm coming from Java where everything is enclosed in a class body, so I'm thinking JavaScript might have something similar to that or some work around that mimics it.
All you're doing in your code is adding a property named
CONSTANT
with the value1
to the Function object named Foo, then overwriting it immediately with the value2
.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
?Not quite what you're after though.
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'.
You must make your constants like you said :
And you access like that :
or
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 :
If you're using jQuery, you can use $.extend function to categorize everything.
Also with namespaces
Your constants are just variables, and you won't know if you try and inadvertently overwrite them. Also note that Javascript lacks the notion of "class".
I'd suggest you create functions that return values that you need constant.
To get the taste of Javascript, find Javascript: the Good Parts and learn the idiomatic ways. Javascript is very different from Java.