Tag Archives: Objects

Namespace, Encapsulation in JavaScript

I’ve had several discussion recently some of the more advanced features of JavaScript, such as functions as return values, namespaces, encapsulation, etc. In order to demonstrate some of these things, I contrived a simple example of a dependency injection tool.

Never mind that dependency injection is not really a relevant pattern in JavaScript or other dynamic languages. It just fit all the pieces I wanted to demo. The Rhino JavaScript engine was used to run and test the example.

For more on how this stuff works, check out Douglas Crockford’s JavaScript: The Good Parts

//ObjectMap namespace
var ObjectMap = function (){
    var that = this;

    that.container = function () {
        var registry = {};
        var fact = {};

        fact.register = function (name, constructor) {
            registry[name] = constructor;
        };

        fact.getObject = function (theType) { 
            return registry[theType]();
        };
        return fact;
    }();
   
    return that;
}();

//Dog constructor, with encapsulated private name
var Dog = function () {
    var d = {};
    var name = "spot";
    d.getName = function () {return name;};
    d.setName = function (val) {name=val; return d;};
    d.speak = function () {return d.getName() + " barks";};
    return d;
};

//register Dog with the DI tool
ObjectMap.container.register("Dog", Dog);

//get and use an object function the DI tool 
var munson = ObjectMap.container.getObject("Dog");
munson.setName("Munson");
print(munson.speak());

Arrays as Objects in Javascript

Rhino Prompt…

js> a[0] = 1;
js> a.print = function () {for(var e in this) print ("a[" + e + "] = " + a[e]);};

function () {
    for (var e in this) {
        print("a[" + e + "] = " + a[e]);
    }
}

js> a.print();
a[0] = 1
a[print] = 
function () {
    for (var e in this) {
        print("a[" + e + "] = " + a[e]);
    }
}