Sunday, February 28, 2010

Practical Object-Oriented JavaScript

In my last post, I provided insight into a object oriented design pattern for JavaScript that I've been using. In this post I want to show a practical implementation of the design pattern.

In the example below I have implemented the abstraction of a base class, Vehicle, with different sub classes: Car, Bike and Truck. The goals I have set out to illustrate this are:
  1. declare public methods in the base class, to be inherited in the different vehicle types
  2. define public variables, accessed through public methods (able to be overloaded)
  3. define a private variable, only utilized within a method from the base class unable to be modified unless overloading the public class calling it
  4. create a constructor that inits and requires arguments
  5. create a constructor in the base classes that overloads an argument ONLY if present
  6. simulate the 'super' call from within the constructor, like in Java

The model:

Vehicle [Parent]
   |
   +--- Car [Child]
   |
   +--- Bike [Child]
   |
   +--- Truck [Child]

The Code:

The organization of the code above has the base class as well as the sub classes within ONE closure. This means that private variables within this closure are directly accessible to other sub-classes as well, in effect making those private variables act like Java's 'protected' variables to the sub classes, and remaining invisible to the global NS.

Equally acceptable is breaking out the various subclasses into their own separate closures ((function(){****})()), but then of course the private variables available in the base class, are not directly available in the extending object's scope. If the base class has a required private variable that needs to be accessed from inheriting classes, there should be a public helper method (appended to the prototype) to access it.

Now let's see an example of using the defined classes:

This code prints out:

VEHICLE is a CAR, Model is a Honda Civic
VEHICLE is a CAR:SPORTS CAR, Model is a BMW m3
VEHICLE is a CAR:FAST SPORTS CAR, Model is a Porsche Turbo
VEHICLE is a BIKE, Model is a Ducati 999
VEHICLE is a TRUCK, Model is a Chevy Silverado 1500

If you've understood the model so far I'd appreciate any feedback. Same goes for anyone having difficulty understanding what i'm getting at. I'm new to blogging and I want to make sure that what i'm writing is as clear and straight-forward as possible.

In my next post I will share what I have found to be the basics for a JavaScript 'framework', and possible package structures.

2 comments:

Matthew said...

This is exactly what I was looking for, thank you for putting the time into it!

Nirvana Tikku said...

Thanks, Matthew. Glad it helped!

Post a Comment