5 reasons to write object-oriented (oo) javascript
To write hard as a rock javascript, the first thing you need to do is to object-orient your code. I do not mean to have a class structure that could stand the passage of a sandstorm in the Sahara but a light and useful structure that will let you work elegantly.
This article does not explain the techniques behind the reasons. It is written for the sake to make you change the way you develop in javascript.
Go read this article if you want to see some code.
1. Packages/namespaces : no more 152 characters prefixes to ensure uniqueness
Packages/namespaces (packages = java, namespaces = .NET) are not the greatest thing since slice bread (did you forget about kool-aid?) but they are the handiest solution to avoid methods, objects or constants to have the same name. I give you a simple example.
I have two methods :
- one that truncates a string of its last character (who wants to do that???)
- one that truncates a number of its decimals
I would write these methods :
- truncate(theString)
- truncate(theNumber)
The problem is that they have both the same signature. How can javascript differenciate the two and call the good one? It can’t.
With packages/namespaces, I could have the following signatures to differenciate them.
- com.CompanyName.String.truncate(theString);
- com.CompanyName.Number.truncate(theString);
Of course, I could have done it a million ways (extending String and Number objects, give them different names, etc) but for the purpose of the demonstration, I have done it that way.
2. Work locally : forget about global variables circa 1987
Global variables are prohibited since 1992 by GVIP (Global Variables International Police). Every variable of that type is seeked and destroyed by them. With javascript, the difference is that a global variable is not “global to the entire application” but global to a page. That’s the gray zone. There’s no strict law against that and people think that it’s OK to do so. They are wrong! A web application that heavily relies on javascript would have dozens of dozens of global variables and would soon become a 3500 pieces puzzle.
Object-oriented javascript allows you to work locally on each variable by making it static (shared for .NETters) or using closures (subject of another article soon!) within an object.
3. Ajax : be a part of web2.0
You want to be the next golden-boy of the web2.0 era? Better start using Ajax now. But wait! Ajax is a mess with all of those callback, failure and timeout functions here and there. Will it stop me from being a billionaire?
No. Object-oriented javascript permits you to stay clean by encapsulating all those ugly functions in objects. Hey, here you’ll need closures too! The last step you need to do is to stay away from drugs. Drugs are bad for your health and they could kill you before you reach your goal. Did I mention “Don’t run with scissors”?
4. Inheritance : for greater powers
I wouldn’t recommend you to use inheritance just to impress women. Inheritance is far too complex for its benefits (you won’t get more women) unless you have a very complex application. And by complex, I mean more complex than building a space shuttle.
Now you are warned. Inheritance is the “most common” principle behind object-oriented and can be implemented in javascript. No, you won’t have the handy extend/inherits or whatever statement in oo language. Maybe this will keep you from over-designing your code so it’s not that bad after all.
5. The future : javascript is already there
Javascript is a step ahead of a lot of programming languages. Sure, it is copied on such and such obscure language but it is the most widely known language that first used closures, functionnal programming, untyped variables and so on.
Java programmers, in their glass tower, think of javascript as a disordered mutant of their beloved language. They are wrong! Javascript only shares its syntax. The most recent versions of Java are now implementing closures and varargs. Looks like the natural selection from Evolution theory has done it again.
If you want to see code for doing object-oriented javascript, read this article.


I’m not sure to fully understand #2. Do you mean like if you want to declare an enum inside your class and then useg it outside of the object like this : myObject.emotionalState=TheClassName.EmotionalStates.Happy ?
Yes and no. I mean that instead of keeping the state of an ajax request in a global variable (example), you can keep it local to your class without having to bother about who touched the variable.
A very good article, but I feel that anyone who knows a bit about JavaScript would like an example.
I’m not saying this is perfect, but its roughly what I use for most of my scripts…
————————–
var myJavascriptObject = new function () {
this.init = function () {
myJavascriptObject.myFunction();
}
this.myFunction = function () {
}
addLoadEvent (function() {
myJavascriptObject.init();
});
}
————————–
PS: That addLoadEvent comes directly from ’simonwillison.net’ - search on Google.
For a more fuller example, please read…
http://www.craigfrancis.co.uk/features/code/popUpWindows/
An interesting read. I would have added a link to a Javascript OO tutorial for the uninitiated. One that you thought was a goody. Just a thought!
was a pretty quick read… i expected see more examples though.
Craig, there are two a darksides to your technique.
First, you can’t create more than one instance of an object because you are directly assigning the class to a variable.
Second, because you are not using prototypes, it uses more memory because each instance of a class will have its own method instead of using a reference to a single method.
Take a look at to see how I do it (might not be the best way) : http://www.javascriptkata.com/2007/03/23/how-to-create-objects-in-object-oriented-javascript/
Thanks for your comment!
Hi Dan,
While you are correct about not being able to create multiple instances… I have not been in a position where I need to have this feature. Typically it is only being used to help create a single name space for the code.
Have you got any examples where multiple instances are useful?
As to the memory requirements… I take this is related to having multiple instances of the main object (a copy)… in which case, I still don’t think this is an issue for me, as I only have one instance of each object.
Hi Craig,
I made another post where I explain how to do classes in javascript : How to create objects in object-oriented javascript.
An example? If I have a list of contacts, every contact should be a different instance of a class. This way, they share their methods and properties and take less memory.
With your technique, it creates a global variable and these variable can be really difficult to track. But I have to admit that I used your technique myself a lot before switching to the new one.
I’d say that even if you don’t need multiple instances, you should encapsulate (when possible) your functions in class. It won’t change nothing to javascript but it will be easier to maintain.
Thanks!
Hi Dan,
Fair enough… I’m sure that its valuable if you are doing allot of work in JavaScript.
Personally I tend to keep the JavaScript usage to a minimum, as I find that most websites I build only need the odd little helper script.
But its handy knowing as many different methods as possible… you never know what the next project might bring.
Thanks
A lot of people tends to keep javascript as minimal as possible. I did it for a long time.
But the reason why I started this site is that I saw more and more advantages in using javascript. It makes my applications faster, cleaner and more user-friendly.
But there’s also hundreds of reason not to use it…
Ill second that… if its an ‘intranet’, a closed environment, then its usually fine to use JS to its full power… but when you get it onto the internet, it can start to cause all sorts of accessibility issues.
That’s why I quite like the unobtrusive method… sometimes known as progressive enhancement…
http://onlinetools.org/articles/unobtrusivejavascript/
NOTE: Anyone reading that article should perhaps not pay that much attention to the specific examples… but the theory is spot on.
At the end of the day… if it works well in standard HTML, then keep it that way.
One thing I have found with screen readers, if the user requests to follow a standard HTML link, the new page will load and start being processed… but if its done with JavaScript, most of the time, the JavaScript will trigger, but the screen reader will sit there and do nothing… the user has to wait, as they might think that the new page is taking a while to load, but eventually they will have to investigate on what has happened.
I once did a website which hi-jacked all links, whereby it replaced the page content, instead of reloading the whole page, the result… a disaster… the back button was broken, users could not copy links to specific pages, the page loaded in a strange way (middle bit changed, which freaked out some users)… the alternative, without JS, seemed to load just as quick… so why bother?
But that was a bad example… there are many other examples which are useful… for example a hidden block of text (like the terms and conditions for a competition) which is displayed on request…
http://www.craigfrancis.co.uk/features/code/jsLinkedWidget/
manufacturer ultram vera ultram