JavaScript namespace support

July 3, 2007

Following up to my previous post about window.onload problems with JavaScript, the other problem I encounter with JavaScript is its lack of namespace support. JavaScript has no concept of namespaces, so there are bound to be conflicts between libraries unless you get lucky and all your JavaScript library authors picked different function and global variable names.

To solve this problem, you can do something rather funky and wrap everything in a function with the same name as the JavaScript library file. Thus, magical JavaScript namespaces, sort of. Here’s the new and “improved” script.js file:

var TestScript = function () {
    return {
        displayListings : function () {
            TestScript._buildStuff(
                "place_to_put_stuff",
                "Some stuff and things"
            );
        },
        _buildStuff : function ( id, text ) {
            var li = document.createElement("li");
            li.appendChild( document.createTextNode(text) );
            document.getElementById(id).appendChild(li);
        }
    };
}();

The rest of the script.js file is the same, with the exception of changing every instance of displayListings to TestScript.displayListings. Notice that even within the TestScript “namespace” you have to refer to _buildStuff by it’s full name.

This seems like a neat idea, although I haven’t tried it for anything real. I am curious how it would work when building a larger-scale set of home-grown JavaScript libraries. For the enterprise development environment, you have to either enforce using this solution or enforce some sort of long naming convention.

function TestScript_displayListings() {
    TestScript__buildStuff(
        "place_to_put_stuff",
        "Some stuff and things"
    );
}

Both options require enforcing a style and best practice across your enterprise, which means that you have to actually enforce something, which means that it probably won’t get enforced (unless you have free time to enforce things, which means you’re not very busy, which means you should probably get downsized). Which one do you think is easier to enforce?

Posted by Gryphon Shafer on July 3, 2007 3:18 PM | | Comments (0)

Post a Comment

After posting a comment, it will have to be approved before it's displayed on the site.

View from WebCam

Current View from Home

Recent Posts

Blog Categories

Archives

Syndication Feeds

Contact Information

J. Gryphon Shafer
AIM: ShaferGryphon
ICQ: 63254641
YIM: GryphonShafer
Skype: gryphon.shafer
Jabber: GryphonShafer
MSNIM: gryphonshafer
PerlMonks: gryphon
CPAN: gryphon
PGP ID: CBE9C7F0

Presentation