Object Oriented Programming (OOP) Primer

What is Object Oriented Programming?  Why use Object Oriented Programming?  How does Object Oriented Programming apply to JavaScript?  Those are the questions I am going to try and answer for you.

What is Object Oriented Programming?

[W:Object Oriented Programming] (OOP) in the simplest of forms is grouping all of the data and functions that operate on a particular thing together.  An example might help.  Suppose you were told to build a banner that changed content at regular intervals and the content for the banner was to be retrieved from an http URL.  We know we are going to need a variable to hold the change interval for the banner.  We will probably need a variable to hold the URL that we get the banner content from.  We might need a function to send the request for the new banner data.  We might need a function to render (display) the new banner data.  And of course we need some sort of way to control it.

Now we know all of the parts that are required to build the dynamic banner.  So now lets design our object.

var DBanner = Class.create( {
    /*
     * This is the constructor for DBanner
     * @param interval How often in ms do we refresh the banner
     * @param url The url that has the banner content.
     * @param bannerId The id of the html element to set the url contents in
     */
    initialize: function(interval, url, bannerId) {
        this.interval = interval;
        this.url = url;
        this.bannerId = bannerId;
        // Start the refresh cycle
        this._nextInterval();
    },

    /**
     * This function fetches the new banner content
     */
    refreshBanner: function() {
        new Ajax.Request( this.url, {
                            onSuccess: this._handleBannerResponse.bind(this)
                           } );
    },

    /**
     * This is the handler for the Ajax request dispatched in refreshBanner
     * @param [XmlHttpTransport] response The xmlHttp response object
     * @private
     */
    _handleBannerResponse: function(response) {
        $(this.bannerId).innerHTML = response.responseText;
        this._nextInterval();
    },

    /**
     * Trigger the next refresh of the banner
     * @private
     */
    _nextInterval: function() {
         setTimeout( this.refreshBanner.bind(this), this.interval );
    }
} );


As you can see in this example all of the data ( interval, URL, and bannerId ) are contained in the DBanner object.  When you are ready to use the dynamic banner all you have to do is instantiate an instance of the object like the following:

new DBanner(5000, "http://www.yahoo.com/", "myBannerDivId" );

As an alternative I could have simply defined global functions and variables to hold all of the data related to the dynamic banner but using an object keeps everything together which is another nicety when you use Object Oriented Programming (OOP).  If I used the global function approach everything I just showed you would work the same way.

Why use Object Oriented Programming (OOP)?

If you use Object Oriented Programming (OOP) all of you data and functions will be grouped in an object which will make it easier to perform maintenance on you code (bug fixes) and more importantly if you need to reuse some of your existing behavior it is much easier.  Lets look at an example of reuse.

Suppose you were asked create a html window display that changed at regular intervals.  The window is not a window in the traditional sense but simply a javascript div that is displayed on top of the existing page.  This sounds a lot like our DBanner we built above except it needs to build and display a div on top of the page with the contents of the url.  Lets build a new object that extends (adds some more behavior) to the original DBanner object.

var DWindow = Class.create( DBanner, {
    initialize: ($super, interval, url ) {
        $super(interval,url,'js-window-contents',);

    },

    _buildJSWindow: function() {
        if ( !$('js-window') ) {
            $(document.body).insert( '<div id="js-window"><div id="js-window-contents"></div></div>' );
        }
    },

    _handleBannerResponse: function($super,response) {
        // Nuild and display the javascript empty window
        this._buildJSWindow();

        // Call the super class to render the html
        $super(response);
    },

} );

As you can see, all we had to do was add some code to build the javascript window used to display the html content.  By extending the DBanner object we had relativley little new code to write and test.

If we had used global functions for the DBanner then we would need to copy all of the functions to a new file and make changes to the copy.  The problem with this approach is it makes it much harder to fix bugs since we now have remember to update both copies of the functions.

Comments 2

  • I’m designing a site using OO (in PHP5). The problem is that some actions, like getting the current ‘user ID’ (of the user currently logged in) take more than one line of code as I have a ‘login session’ object.

    The problem is that a global function which just returns the ‘user ID’ as an integer, e.g. ‘get_current_user_id()’ would make it easier, but this isn’t OO.

    I’m not sure if a 100% pure OO approach is ALWAYS sensible. I do try and minimise global functions (I only have warning() and error() functions at the moment, but what to do about really common functions such as the ‘get_current_user_id’ requirement?

    Any ideas? 🙂

  • This site is about developing Object Oriented JavaScript, but you can apply the same techniques to php as well.

    As far as your global function, why not create a utility class and stick all of your global functions in it. If you have more information about the user then you could create a user object to that has a getId function and others as needed.