Where to declare class constants? Where to declare class constants? javascript javascript

Where to declare class constants?


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.


You must make your constants like you said :

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

And you access like that :

Foo.CONSTANT1;

or

anInstanceOfFoo.__proto__.constructor.CONSTANT1;

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 :

Foo.prototype.CONSTANT1 = 1;


IF the constants are to be used inside of the object only:

function Foo() {    var CONSTANT1 = 1,CONSTANT2 = 2;}

If not, do it like this:

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

It's much more readable and easier to work out what the function does.