Useful Javascript OO pattern
Category: Blog

I’ve spent the majority of the day (and a good chunk of the evening) refactoring the HTML, CSS, JS, and PHP for the Yahoo! Web Messenger products (we are known internally as the “Eden Team“). Being that all but one of our products (the messenger inside Yahoo! Mail, which still uses a Flash based SDK for the network transport) we developed on this team are mostly Flash based (Flex/AS3 technically), the non-Flash based components have badly needed some love for a while. Before digging into the Javascript I decided to browse around for a better OO pattern for Javascript classes. Not being someone who likes coding in Javascript much (part of why I joined this team), it’s not something I have been staying current on lately. Looking at the code for SWFObject 2.0 I discovered they had a pretty clever approach which gives you public and private class variables, public and private methods, and even something akin to a static initializer. Here’s a bit of sample code to illustrate the concept:

var myObj = function() {
    // private instance variables
    var foo = 33;

    // pseudo static initializer
    var staticInitializer = function() {
        // do some code here, will run only once
    }();

    // private method
    function foobar() {
        // do something
    }

    // public api
    return {
        publicMethod: function() {
            // do something
        },

        publicVariable: 42,

        publicMethod2: function() {
             // do something
        }
    }
}();

None of the above was new to me, but I had never seen it put all together like that. I liked it enough that I’ve adopted it as my preferred pattern for JS code going forward. Now, once I get the PHP code looking respectable I can finally sleep a little better at night!

Update:
Yes, the Eden team is the same team which is developing myM, and no, I won’t get you an invite (not this year at least).

Tags: ,

3 Responses to “Useful Javascript OO pattern”

  1. billgoates says:

    This pattern is called a namespace, not a class. You cannot inherit from, or extend this object. It’s used for api’s or function libraries.

    It’s possible to write classes with private and public members, but they tend to be slower on creation.

  2. [...] Christmas day) visiting family back in the midwest. Since then, I’ve been busy getting some refactoring done at work, writing a Safari SIMBL plugin for Yahoo! Search, as well as catching up on some [...]

  3. Bertold von Dormilich says:

    > This pattern is called a namespace, not a class. You cannot inherit from, or extend this object.

    it’s an object, of course you can inherit from that. though you only have access to the public members.

Leave a Comment

Spam Protection by WP-SpamFree