Static Classes in JavaScript with Immutable Members

Okay, we know that JavaScript doesn't actually have classes. Prototypes, yada yada, life goes on. So while Static Classes in JavaScript don't exist, let's talk about them anyway!

Reminder: Static Classes

Static classes are classes that are not instantiated. For example, the Math class in JavaScript.
var number = Math.pow(2,3); // Math is a static class
var john = new Person();    // Person is not a static class
john.say_hi();              // Invoke the say_hi method
Since the say_hi method is called via the Person object john, it is not static. In contrast, the pow method is called directly from the Math class itself.

When to use Static Classes?

The decision to use a static class depends all on personal preference and readability. The downside to static classes is that the class name populates the global namespace. A static class can easily be converted to a non static class, so if you change your mind, it's really not a big deal.

A Sample Static Class

// Start off with an empty object
var Physics = {};

// Begin populating with attributes or methods
Physics.get_velocity = function(vi, a, t){
    return vi + a * t;

/* Now we can use the get_velocity method without 
 * instantiating a Physics object
var velocity = Physics.get_velocity(5, 9.81, 10); 

Creating Immutable Properties

The term "immutable" in JS must be taken with a grain of salt. Few items are truly immutable. Not even the methods of the official JS Math class are protected.
/* My plot to sabotage the data of my colleagues 
 * and win the Nobel Prize!!!
Math.pow =  function(a,b){return a + b};

Math.pow(2,3)  // 5, not 8! Bwahahah!
But hey, an extra layer of security is better than nothing, right? By using anonymous functions, we can (better) protect the values of properties that we do not want changed.
// Create our static class, starting with an empty object
var Physics = {};

Physics.prop = function(){
    return {
        g: 9.81,
        pi: 3.14

Physics.constant = function(val){
    return Physics.prop()[val];

Physics.constant("pi"); // 3.14

Physics.prop()["pi"] = "LOL";
Physics.constant("pi"); // 3.14
This obviously is not a strong degree of protection, but I do honestly believe it's better than nothing. Suggestions and improvements are welcomed! July 11, 2011
About the Author:

Joseph is the lead developer of Vert Studios Follow Joseph on Twitter: @Joe_Query
Subscribe to the blog: RSS
Visit Joseph's site: