Constants in javascript


Global constants

Ouch! That one hurts!  global variables are prohibited since 1992 by GVIP (Global Variables International Police). But sometimes, a man gotta do what a man gotta do. If you really can’t find any better solution, use this one.
[source:javascript]
var DISPLAY_TYPE_SMALL = 0;
var DISPLAY_TYPE_BIG = 1;

[/source]

Class constant

If you already know how to create objects you have to use the class functions technique (also knows as static or shared functions) to create a class “constant”.
[source:javascript]
// Create the class
function TheClass() {
}

// Create the class constant
TheClass.THE_CONSTANT = 42;

// Create a function for TheClass to alert the constant
TheClass.prototype.alertConstant = function() {
// You can’t access it using this.THE_CONSTANT;
alert(TheClass.THE_CONSTANT);
}

// Alert the class constant from outside
alert(TheClass.THE_CONSTANT);

// Alert the class constant from inside
var theObject = new TheClass();
theObject.alertConstant();

[/source]

As you saw, you can’t access the constant using the this variable (a reference to the current object) because the constant is defined on the class only and not the object.

Class enum

Sometimes, constants are not enough. You need to regroup them to be more logical. Example? I have three different display type : small, medium, big. I could do this
[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE_BIG;
}

// Create constants
TheClass.DISPLAY_TYPE_SMALL = 0;
TheClass.DISPLAY_TYPE_MEDIUM = 1;
TheClass.DISPLAY_TYPE_BIG = 2;

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE_SMALL;
[/source]

It works but they are not logically grouped. I would prefer to use an enumeration (enum)
[source:javascript]
// Create the class
function TheClass() {
// Initialize the display type to big
this.displayType = TheClass.DISPLAY_TYPE.big;
}

TheClass.DISPLAY_TYPE = {
small : 0,
medium : 1,
big : 2
}

// Assign the small display type to the object
var theObject = new TheClass();
theObject.displayType = TheClass.DISPLAY_TYPE.small;
[/source]

0 comments: