Friday, August 10, 2012

js singleton boilerdish

(Improved version as of early 2014)

This is mostly just for future reference for myself (hence the cutesy name "boilerdish" that I can Google on...)

There are several patterns for making JS objects. One of my favorites is:

var someObject = new function(){
    this.someVariable = undefined;

    this.init = function(){
        alert("started up");
        someObject.someVariable = true; //don't rely on meaning of "this" too much!
    };
}

$(document).ready(someObject.init);

(Also sometimes I like to throw in the diagnostic logging stuff I wrote about here)

Caveats: this pattern doesn't provide much "privacy" for members, so it's not good for defensive coding. It's also kind of assuming a "singleton" use, but I find that pretty common and useful. (Also, given how frustrating "it depends on what this 'this' is this time" can be, the fall back of being able to refer to  "someObject.someVariable" out of the global space, rather than relying on delegates so that something like "this.someVariable" can work, is extremely helpful...) It does mean that there can just be a single entry in the generic Window namespace, which is always a plus.

No comments:

Post a Comment