Where to declare class constants?

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 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 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

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’.

First, I recommend moving your class declaration inside of an IIFE. This cleans up the code, making it more self-contained, and allows you to use local variables without polluting the global namespace. Your code becomes:

var Foo = (function() {
  function Foo() {
  }

  Foo.CONSTANT1 = 1;
  Foo.CONSTANT2 = 2;

  return Foo;
})();

The problem with assigning constants directly to the class as attributes is that those are writable. See this snippet:

var output = document.getElementById("output");

var Foo = (function() {
  function Foo() {
  }

  Foo.CONSTANT1 = 1;
  Foo.CONSTANT2 = 2;

  return Foo;
})();

Foo.CONSTANT1 = "I'm not very constant";

output.innerHTML = Foo.CONSTANT1;
<div id="output"></div>

The best solution I have found is to define read-only properties for accessing the constants outside of the class.

var output = document.getElementById("output");

var Foo = (function() {
  const CONSTANT1 = "I'm very constant";

  function Foo() {
  }

  Object.defineProperty(Foo, "CONSTANT1", {
    get: function() {
      return CONSTANT1;
    },
  });

  return Foo;
})();

Foo.CONSTANT1 = "some other value";

output.innerHTML = Foo.CONSTANT1;
<div id="output"></div>

(Technically you could ditch the const CONSTANT1 statement and just return the value from the property definition, but I prefer this because it makes it easier to see all the constants at a glance.)

Read More:   Javascript search inside a JSON object

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.

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;
    }
};

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 😉

Read More:   can I include a text/template script from a src?

Yea and I use _ before static method – it is not needed, I don’t know why I started to do that 🙂


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts