views:

137

answers:

6

What object oriented design patterns do you use in your application's javascript, and why?

Feel free to post code, even if there is no formal design pattern attached to it.

I have written plenty of javascript, but I have not applied much object orientated patterns to what I am doing, and I am sure i am missing a lot.

+1  A: 

I am a fan of the Module Pattern. It's a way of implementing extensible, non-dependent (most of the time) frameworks.

Example:

The framework, Q, is defined like this:

var Q = {};

To add a function:

Q.test = function(){};

These two lines of code are used together to form modules. The idea behind modules is that they all extend some base framework, in this case Q, but are not reliant on each other (if designed correctly) and can be included in any order.

In a module, you first create the framework object if it does not exist (which is an example of the Singleton pattern):

if (!Q)
    var Q = {};

Q.myFunction = function(){};

That way, you can have multiple modules (like the one above) in separate files, and include them in any order. Any one of them will create the framework object, and then extend it. No manual need to check if the framework exists. Then, to check if a module/function exists in custom code:

if (Q.myFunction)
    Q.myFunction();
else
    // Use a different approach/method
SimpleCoder
This looks extremely useful. how are you using this in your code? thanks for sharing!
ming yeow
I used it on a recent project I did where I had separate JavaScript files for the common functions, UI, and two other specialized mechanisms. All the files added functions to the same framework (defined using the method I showed above) and they called the functions like I did above.
SimpleCoder
One of the main uses for this type of technique is avoiding pollution of the global namespace. What pollutes more? A single `Q` framework variable, or dozens and dozens of functions and variables?
SimpleCoder
+1  A: 

I really like jquery's method chaining pattern, allowing you to call several methods on one object. It makes it really easy to perform several operations in a single line of code.

Example:

$('#nav').click(function() {
   $(this).css('color','#f00').fadeOut();
});
GSto
right - agreed! have you developed your own custom methods that work these way before?
ming yeow
+3  A: 

The following are three popular JavaScript patterns. These happen to be easily implementable because of closures:

You may also want to check out:

The following is a Google I/O talk from 2008 presented by Diaz, where he discusses some topics from his book:

Daniel Vassallo
nice! curry looks like a way smarter way to do some of the generalization i was trying to do. already using simple forms of module and memoization - but need to study these examples to push how i currently do it. Which ones do you use the most?
ming yeow
@ming: Probably, it's the module pattern. Very easy to implement and to understand, and it comes with some cool features, including namespacing and private variables/methods.
Daniel Vassallo
+1  A: 

The singleton pattern is often very helpful for 'encapsulation' and organization stuff. You can even change accesibility.

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

cleanest way to implement a singleton in javascript

CrazyJugglerDrummer
awesome - This is the one i use all the time! But that is just about the extent of my javascript OO. ;)
ming yeow
+1  A: 

I really like the Decorator pattern with jQuery plugins. Rather than modifying plugins to meet your needs, write a custom plugin that just forwards requests and adds additional parameters and functionality.

For example, if you need to pass a set of default arguments around all the time, and you need slightly-different behavior that ties into business logic, write a plugin that does whatever pre and post work is necessary to suit your needs and passes your default arguments if those particular arguments aren't specified.

The main benefit of this is that you can update your libraries and not worry about porting library changes. Your code might break, but there's at least the chance that it won't.

Stefan Kendall
This sounds like a great idea. Do you have an actual example on the code to do the actual extending? Even a simple example will help everyone greatly.
ming yeow
+1  A: 

@ming From a practical standpoint, I'm confident you have the requisite skills to hone your OO JavaScript skills. I mean, you already know the fundamentals and that's very important! You're probably not trying to write the next jQuery, but what you do want is a chance to move away from the procedural mess that many of us make of our JavaScript code.

Well, here's a practical example from a non-flash dashboard speedometer gauge written with Plain Old JavaScript Objects (POJOs) for its domain model, jQuery for its service layer and Raphael for SVG image manipulation. Download the example for further study and details. For simplicity sake, I'll focus on the Domain Model, since my gut tells me that's what you're interested in.

Take for example a domain model consisting of a Speedometer, Fuel Gauge and Temperature Gauge. Each have something in common. Namely, they are all derived from a gauge. So, each will have a Gauge base class. This should set the scene:

Constructor

Speedometer = function (gaugeID) {
    //[State]
    var mph;

    //[Initialization]
    this.SetGaugeID(gaugeID);

    this.CreateGauge(); 
    this.SetMPH(0); //initialize control
}

Inherit base functionality from Base Class (Gauge)

//Inherit gauge functionality
Speedometer.prototype = new Gauge();

Do pay close attention to how the base class was inherited. This is called prototypical inheritance. It's a little different from classical class based inheritance. But, not so different as to bar you from structuring your code in a DRY way.

Add some Properties (Accessors)

//[Properties]
Speedometer.prototype.SetMPH = function(mph) {
    this.mph = mph;
}

Put some Methods to "work" for the Speedometer class

//[Methods]
Speedometer.prototype.Accelerate = function() {
    //Do some work here...
}

Now for the fun part. We so deliciously put together our Speedometer class. Now, let's take it for a spin:

//Create new speedometer gauge instance
var speedGauge = new Speedometer("speedometer");

//Warm up your engine
speedGauge.SetMPH(5);

//Time to put the pedal to the metal
speedGauge.Accelerate();

Well, hope this gives you an idea of one possible way to structure your JavaScript code. As you can see, you already have the basics. You just need to learn to love prototypical inheritance and you're good-to-go.

Jacob Darby