Static Methods in Javascript

Sep 2nd, 2008 | Filed under JS OOP

Object Oriented Javascript (OOP) Part 2

I would like to build on the Object Oriented Javascript page I talked about in an earlier post.  I explained how to use inheritance and polymorphism but sometimes a static function ( that is there is only one copy of the function no matter how many objects you create) can be real handy for utility functions.

If you recall the class hierarchy before Shape was the base class and Circle, Square, Triangle were subclasses well now lets add some static functions to the Shape class.  This example might be a little bit of a stretch but it will illustrate my point.

Shape.getFormula = function(type) {
    if ( type == 1 ) return "l * w";
    if ( type == 2 ) return "1/2 * b * h";
    if ( type == 3 ) return "pie * r^2";
}

If you want to access the static method you have to invoke it as follows:

Shape.getFormula( 1 );

If you were to try to access it as an instance method it will be undefined.

new Circle().getFormula(3);

You have static functions in any namespace not just inside an objects namespace.  A namespace in java is just any object that you like.  There is a global namespace also this is where you functions and definitions will go if you don’t specify a namespace.

Here is an example of a static function declared in the global namespace.

var warnUser = function(msg) {
    alert(msg);
}

Equivalent:

function warnUser(msg) {
    alert(msg);
}

If you always put your objects and static functions in a namespace the likelihood of a name clash is greatly minimized. If I were to declare the warnUser function in a namespace I might do something like this:

var user = {};  // Declare my namespace
user.warn = function(msg) {
    alert(msg);
}
  1. AerenCarter
    Nov 14th, 2011 at 18:34
    Reply | Quote | #1

    Hey $author , I dont usually comment on these things but your post, Static Methods in Javascript | justjs.org , was really well written and I enoyed reading it. Keep it up!!