HomeBlogObject oriented programming in JavaScript

Object oriented programming in JavaScript

I'm pretty sure you know the Foo.prototype.bar = function(){ ... } syntax for declaring object methods, and also the Bar.prototype = new Foo stuff for setting up inheritance.  You also probably know that Prototype.js and jQuery have devised new, shorter/cleaner ways to declare objects.

In the article below I'm presenting my own, which I developed around 2005 and kept refining it.  The current "syntax" is used in DynarchLIB (although not in the released version, which still uses the old eval()-based hacks).

In short, to define an object now I say:

DEFINE_CLASS("MyObject", BaseClass, function(D, P){

        _something: [ "something", "Default Value" ]

    P.getSomething = function() {
        return this._something;


var obj = new MyObject();
alert( obj.getSomething() ); // shows "Default Value"

var obj = new MyObject({ something: "foo" });
alert( obj.getSomething() ); // shows "foo"

In this article I will describe all knowledge necessary to implement the DEFINE_CLASS "macro", and the code for DEFINE_CLASS itself (which does a lot more magic than can be seen in the above sample).  I'll be touching areas that always created confusion, such as OOP in standard JavaScript, prototype (or how inheritance works), the meaning of the this keyword and inner functions (closures).  If you're not a top JavaScript programmer and want to become one, then this article might be a pretty good start. ;-)

Download article (PDF)

Feedback is very much appreciated!


Page info
2009/08/24 15:05
2009/11/27 17:20
Mihai Bazon
javascript, lexical closures, programming
See also