Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  24] [ 6]  / answers: 1 / hits: 37190  / 14 Years ago, tue, january 25, 2011, 12:00:00

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.


More From » conventions

 Answers
3

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.


[#94071] Saturday, January 22, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackenzihannal

Total Points: 548
Total Questions: 96
Total Answers: 96

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;