Wednesday, February 1, 2012

Creating POJOs in JavaScript

POJO stands for Plain Old Java Object, but in our case, it will be JavaScript instead of Java...Plain Old JavaScript Objects.

Sometimes in your code, you would need to create objects that are just containers for members (in OOP terms, these objects are usually referred to as classes).

As an example:
var dog = function (name, age) {
 return {
       name: name,
       age: age
 };
};
Now you can obviously write all this by hand, but you don't have to because you can write a function that makes use of JavaScript's dynamic nature to do it for you:
var pojo = function () {
    var members = arguments;

    return function () {
        var obj = {}, i = 0, j = members.length;
        for (; i < j; ++i) {
            obj[members[i]] = arguments[i];
        }

        return obj;
    };
};
And this is how it can be used:
var dog = pojo('name', 'age'), // create the POJO
    fido = dog('Fido', 2); // create an 'instance' of the POJO

// fido.name -> 'Fido'
// fido.age  -> 2

The pojo function is pretty straightforward. First we grab a reference to the arguments object (which contains the names of the members that we want to be in our object; ['name', 'age']) and then return a function which will serve as the initializer for our POJO object.

Once the inner initializer function is invoked from the outside (dog('Fido', 2)), we iterate through the member names we got from the initial arguments object to create a new object (obj) containing the member names and the values of the actual arguments that were passed to the inner function as their respective values.

If you only want a single 'instance' of the POJO, you can get away with a one-liner:
var fido = pojo('name', 'age')('Fido', 2);