Object Oriented Javascript · Curiosity is bliss

Curiosity is bliss    Archive    Feed    About    Search

Julien Couvreur's programming blog and more

Object Oriented Javascript


Javascript is not yet a full Object Oriented language (but future versions probably will come closer), but I was suprised to discover that it already offers some object oriented facilities, that are described in the articles linked below.

Here is the gist of the syntax:

function MyObject() {
   // This is the constructor. It can take parameters if you want
   this.myAttribute = 0;
   this.setAttribute = setAttributeImpl;

function setAttributeImpl(param1) {
   this.myAttribute = param1;

What differentiates the MyObject constructor from a regular function is actually up to the caller. MyObject() needs to be called with new for it to make an object.
For example, you would do:

var obj = new MyObject();

A nice intro on the subject.
Also, if you want to add attributes and methods to objects that you don't own, the prototype attribute is your solution.
Another detailed article on the subject (free registration required). Update: the link is now available in the IBM developerWorks > Web architecture section, as Creating and using JavaScript objects.

Personally, I liked to store my object-like structures by creating extra attributes in the DOM (usually with an underscore prefix) and have a naming convention for the methods. The Selector webcontrol uses this trick, but I am considering switching to using javascript "objects" as it might make debugging easier and design a bit simpler.

Update: I posted a bunch of additional advanced Javascript links.


What is name of the IBM tutorial? The link doesn't work, even with the obvious manipulations and there are no pointers that help in searching DeveloperWorks :(

Posted by: Robert Spencer at July 27, 2003 04:46 AM

Indeed ;-)
I think I found the tutorial again. Fixed the link.


Posted by: Dumky at July 27, 2003 11:53 AM
comments powered by Disqus