Simple Solution for JavaScript Object Packages and Namespaces

Most OO programers are familiar with packages.  This enables programmers to group like classes together in a logical order and provide some namespace to avoid class name collisions.

I have seen a variety of JavaScript sugar implementations that are mostly unintelligible.

I like things that are simple and easy to understand.

So, if you have a JavaScript class that looks like:

/**
 * Constructor
 */
com.ryanchapin.Base = function() {

    //
    // Constructor does something here . . .
    //
}

//—————————————————————————-
// Properties:
//

/**
 * Some property
 */
com.ryanchapin.Base.prototype.someProperty;

//—————————————————————————-
// Methods:
//

com.ryanchapin.Base.prototype.doSomething = function() {

    //
    // Do something here . . . .
    //
}

Then all you need to do is add something similare to the following as the top-most block of JavaScript on the page:

<script type=”text/javascript”>

            // Instantiate ‘package/namespace’, containing object
            var com = new Object();
            com.ryanchapin = new Object();

            // Then you can instantiate your objects as follows:
            var baseInst = new com.ryanchapin.Base();

</script>

This will create the ‘container’ object in which your class definitions will reside and help reduce the use of global variables as well as class name and method name collisions.

Leave a Reply