Restored from the original mckoss.com, where this paper was first published in January 2006 (with an update in 2009). The examples still run live in your browser, but in a modern way. The original passed each code sample to eval(), wrote the results into the page with document.write(), and drew the object diagrams by adding methods to every object through Object.prototype. Now each example runs as ordinary JavaScript, and its output and diagrams are built with DOM methods and inserted after the code. The two examples that change built-in objects undo those changes as soon as they finish. If JavaScript is off, you’ll see the same output, captured from the original page’s code. I’ve also removed the ads, comments, and bookmarking widget, moved a book recommendation to the references, and updated links that no longer work. The first version of this paper, from 2003, survives only as a PDF printout, linked in the introduction.

Introduction

The first version of this paper, written in 2003, had several shortcomings, not the least of which was that the techniques described were specific to Internet Explorer. I’ve updated and improved on the original, to document the current state of the art, especially in light of the extensive interest in AJAX technology and the increasing adoption of the FireFox browser. All the examples presented here will follow the ECMA language standards and can be applied to Internet Explorer, FireFox, and ActionScript (in Macromedia Flash).

While early adopters of JavaScript used it as a simple scripting engine to create dynamic web pages, modern web designers have come to use more sophisticated object oriented techniques in building their code. I will present here, both the common paradigms used in object oriented JavaScript programming, and also suggest some helper functions that you can use in your code to streamline the process.

It should be noted that the current design of the JavaScript language, did not fully anticipate or fully implement an object oriented system. That is why the subject is somewhat mysterious and there are various implementations of object oriented programming techniques being used on the web today. I will describe what I believe to be the most main-stream and compatible implementation that fits most naturally into the design of the language.

Object Oriented Programming Goals

I assume that the reader has a basic familiarity with JavaScript, function calls, and the basic tenets of object oriented programming. I consider the three primary goals of object oriented programming to be:

  • Encapsulation - Support for method calls on a JavaScript object as a member of a Class.
  • Polymorphism - The ability for two classes to respond to the same (collection of) methods.
  • Inheritance - The ability to define the behavior of one object in terms of another by sub-classing.

Through a series of examples (which, for the curious reader, are actually snippets of live JavaScript code embedded within this page), I will demonstrate how objects can be used in JavaScript and how these object oriented paradigms can be best implemented. I will cover techniques for:

  • Defining a Class
  • Defining and calling Methods in a Class
  • Defining a Sub-Class
  • Calling the Super-Class constructor from a Sub-Class
  • Overriding Methods of a Super-Class in a Sub-Class
  • Calling a Super-Class method from a Sub-Class

Simple Objects

The simplest object oriented construct in JavaScript is the built-in Object data type. In JavaScript, objects are implemented as a collection of named properties. Being an interpreted language, JavaScript allows for the creation of any number of properties in an object at any time (unlike C++, properties can be added to an object at any time; they do not have to be pre-defined in an object declaration or constructor).

So, for example, we can create a new object and add several ad-hoc properties to it with the following code:

obj = new Object;
obj.x = 1;
obj.y = 2;

Which creates a JavaScript object which I will represent graphically like this:

obj
x1
y2
Object.prototype
constructorObject

The left hand column displays the property name of each available property on the object, while the right hand column displays it’s value. Note that in addition to the x and y properties that we created, our object has an additional property called constructor that points (in this case) to an internal JavaScript function. I will explain prototype properties, below.

Defining a Class - Object Constructors

A new JavaScript class is defined by creating a simple function. When a function is called with the new operator, the function serves as the constructor for that class. Internally, JavaScript creates an Object, and then calls the constructor function. Inside the constructor, the variable this is initialized to point to the just created Object. This code snippet defines a new class, Foo, and then creates a single object of that class.

function Foo()
{
    this.x = 1;
    this.y = 2;
}

obj = new Foo;
obj
x1
y2
Foo.prototype
constructorFoo
Object.prototype
(constructor)Object

Note that we can now create as many Foo type objects as we want, all of whom will be properly initialized to have their x and y properties set to 1 and 2, respectively.

Prototypes Explained

In JavaScript, each Object can inherit properties from another object, called it’s prototype. When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object’s prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype. Each object is associated with a prototype which comes from the constructor function from which it is created.

For example, if we want to create an object, X, from constructor function B, whose prototype chain is: B.prototype, A.prototype, Object.prototype:

Diagram: functions Object, A, and B each point to their prototype objects, which point back via constructor; X's __proto__ is B.prototype, whose __proto__ is A.prototype, whose __proto__ is Object.prototype

We would use the following code:

Object.prototype.inObj = 1;

function A()
{
    this.inA = 2;
}

A.prototype.inAProto = 3;

B.prototype = new A;            // Hook up A into B's prototype chain
B.prototype.constructor = B;
function B()
{
    this.inB = 4;
}

B.prototype.inBProto = 5;

x = new B;
document.write(x.inObj + ', ' + x.inA + ', ' + x.inAProto + ', ' + x.inB + ', ' + x.inBProto);
1, 2, 3, 4, 5
x
inB4
B.prototype
constructorB
inA2
inBProto5
A.prototype
(constructor)A
inAProto3
Object.prototype
(constructor)Object
inObj1

In FireFox and in ActionScript, an object’s prototype can be explicitly referenced via the non-standard __proto__ property. But in standard JavaScript a prototype object can only by directly referenced through the object’s constructor function object.

Defining and Calling Methods in a Class

JavaScript allows you to assign any function to a property of an object. When you call that function using obj.Function() syntax, it will execute the function with this defined as a reference to the object (just as it was in the constructor).

The standard paradigm for defining methods is to assign functions to a constructor’s prototype. That way, all objects created with the constructor automatically inherit the function references via the prototype chain.

function Foo()
{
    this.x = 1;
}

Foo.prototype.AddX = function(y)    // Define Method
{
    this.x += y;
}

obj = new Foo;

obj.AddX(5);                        // Call Method
obj
x6
Foo.prototype
constructorFoo
AddXfunction ...
Object.prototype
(constructor)Object

Polymorphism is achieved by simply having different object classes implement a collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.

function A()
{
    this.x = 1;
}

A.prototype.DoIt = function()   // Define Method
{
    this.x += 1;
}

function B()
{
    this.x = 1;
}

B.prototype.DoIt = function()   // Define Method
{
    this.x += 2;
}

a = new A;
b = new B;

a.DoIt();
b.DoIt();
document.write(a.x + ', ' + b.x);
2, 3
a
x2
A.prototype
constructorA
DoItfunction ...
Object.prototype
(constructor)Object
b
x3
B.prototype
constructorB
DoItfunction ...
Object.prototype
(constructor)Object

Defining a Sub-Class

The standard paradigm, is to use the prototype chain to implement the inheritance of methods from a super class. Any methods defined on the sub-class will supersede those defined on the super-class.

function A()                        // Define super class
{
    this.x = 1;
}

A.prototype.DoIt = function()       // Define Method
{
    this.x += 1;
}

B.prototype = new A;                // Define sub-class
B.prototype.constructor = B;
function B()
{
    A.call(this);                   // Call super-class constructor (if desired)
    this.y = 2;
}

B.prototype.DoIt = function()       // Define Method
{
    A.prototype.DoIt.call(this);    // Call super-class method (if desired)
    this.y += 1;
}

b = new B;

document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>');
b.DoIt();
document.write(b.x + ', ' + b.y);
true, true
2, 3
b
x2
y3
B.prototype
constructorB
(x)1
DoItfunction ...
A.prototype
(constructor)A
(DoIt)function ...
Object.prototype
(constructor)Object

Something to keep in mind is that each time a sub-class is defined, we explicitly call the constructor of the super-class in order to insert it into our prototype chain. So it is important to ensure that no undesirable side-effects will occur when this call is made. Conversely, if the super-class constructor should be called for each instance of every sub-class, code must be explicitly added to the sub-class’s constructor to make this call (as is done in the above example).

An Alternate Sub-Classing Paradigm

As an alternate to using the prototype chain, I’ve developed a method which avoids calling the constructor of a super class when each sub-class is defined. Three methods are added to the Function object:

Function.prototype.DeriveFrom = function(fnSuper)
{
    var prop;

    if (this == fnSuper)
        {
        alert("Error - cannot derive from self");
        return;
        }

    for (prop in fnSuper.prototype)
        {
        if (typeof(fnSuper.prototype[prop]) == "function" && !this.prototype[prop])
            {
            this.prototype[prop] = fnSuper.prototype[prop];
            }
        }

    this.prototype[fnSuper.StName()] = fnSuper;
}
Function.prototype.StName = function()
{
    var st;

    st = this.toString();
    st = st.substring(st.indexOf(" ")+1, st.indexOf("("));
    if (st.charAt(0) == "(")
        st = "function ...";

    return st;
}
Function.prototype.Override = function(fnSuper, stMethod)
{
    this.prototype[fnSuper.StName() + "_" + stMethod] = fnSuper.prototype[stMethod];
}

Repeating the sub-classing example using this new paradigm:

function A()                        // Define super class
{
    this.x = 1;
}

A.prototype.DoIt = function()       // Define Method
{
    this.x += 1;
}

B.DeriveFrom(A);                    // Define sub-class
function B()
{
    this.A();                       // Call super-class constructor (if desired)
    this.y = 2;
}

B.Override(A, 'DoIt');
B.prototype.DoIt = function()       // Define Method
{
    this.A_DoIt();                  // Call super-class method (if desired)
    this.y += 1;
}

b = new B;

document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>');
b.DoIt();
document.write(b.x + ', ' + b.y);
false, true
2, 3
b
x2
y3
B.prototype
constructorB
DoItfunction ...
AA
A_DoItfunction ...
Object.prototype
(constructor)Object

Unfortunately, this technique does not allow for the use of the instanceof operator to test for membership of a super-class. But, we have the added benefit that we can derive from more than one super class (multiple inheritance).

Private Members

Amazingly, JavaScript also can support private members in an object. When the constructor is called, variables declared in the function scope of the constructor will actually persist beyond the lifetime of the construction function itself. To access these variables, you need only create local functions within the scope of the constructor. They may reference local variables in the constructor.

function A()
{
    var x = 7;

    this.GetX = function() { return x;}
    this.SetX = function(xT) { x = xT; }
}

obj = new A;
obj2 = new A;
document.write(obj.GetX() + ' ' + obj2.GetX());
obj.SetX(14);
document.write(' ' + obj.GetX() + ' ' + obj2.GetX());
7 7 14 7
obj
GetXfunction ...
SetXfunction ...
A.prototype
constructorA
Object.prototype
(constructor)Object
obj2
GetXfunction ...
SetXfunction ...
A.prototype
constructorA
Object.prototype
(constructor)Object

I believe, however, that each instance of an object created in this way, has it’s own copy of each local function. The local copy of the function can maintain a copy of the local scope (a closure) of the constructor. This would be rather inefficient for object classes that construct many instances. Experiments with a single (shared) reference to a function reveal that they can only reference variables from a single instance of the class. Since the benefits of using private members is rather limited in the context of JavaScript (which is already lacking any form of type safety), I would not recommend making extensive use of the private member paradigm.

Update (June 2009): I’ve developed a simple library for building JavaScript Namespaces (public domain source code) - for a description see my blog.

References

  • ECMA-262 - ECMAScript Standard Documentation
  • JavaScript Closures - Detailed (if lengthy) explanation of JavaScript closures, along with efficiency concerns especially with the inability of the garbage collector to clean up function calls in the presence of possible closures.
  • JavaScript: The Good Parts - Doug Crockford’s book explains the best parts of the JavaScript language.

Addendum (2026, AI-generated)

This addendum was written by Claude, an AI model made by Anthropic, when the paper was restored in 2026. It is not part of the original paper.

Since this paper was written, the JavaScript language has been extended to directly support the object oriented techniques described above. The examples below are live, just like those in the paper.

Object.create

The ECMAScript 5 standard (2009) added Object.create and Object.getPrototypeOf. With Object.create, a sub-class can be hooked into the prototype chain without calling the constructor of the super-class, which addresses the concern raised in Defining a Sub-Class. And Object.getPrototypeOf gives standard access to an object’s prototype, so the non-standard proto property is no longer needed. Repeating the sub-classing example:

function A()                        // Define super class
{
    this.x = 1;
}

A.prototype.DoIt = function()       // Define Method
{
    this.x += 1;
}

B.prototype = Object.create(A.prototype);   // Define sub-class
B.prototype.constructor = B;
function B()
{
    A.call(this);                   // Call super-class constructor (if desired)
    this.y = 2;
}

B.prototype.DoIt = function()       // Define Method
{
    A.prototype.DoIt.call(this);    // Call super-class method (if desired)
    this.y += 1;
}

b = new B;

document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>');
document.write((Object.getPrototypeOf(b) == B.prototype) + '<BR/>');
b.DoIt();
document.write(b.x + ', ' + b.y);
true, true
true
2, 3
b
x2
y3
B.prototype
constructorB
DoItfunction ...
A.prototype
(constructor)A
(DoIt)function ...
Object.prototype
(constructor)Object

Note that, unlike the original example, B.prototype no longer has its own copy of x, since the constructor of A was never called to create it.

The class Keyword

The class keyword itself took a longer road. ActionScript 3 (2006), which was based on a draft of a new ECMAScript 4 standard, added true classes, but that draft was abandoned in 2008. CoffeeScript (2009) offered a class syntax that compiled into the same constructor and prototype code described in this paper. Then TypeScript (first released in 2012) adopted the class syntax that had been proposed for the next version of the standard, adding compile-time type checking and public and private modifiers, and allowed developers to use classes years before browsers supported them.

That proposal became part of the ECMAScript 2015 standard, which added the class, extends, and super keywords to JavaScript itself. These are, in effect, a direct syntax for the standard sub-classing paradigm: a class is still a constructor function, its methods are still stored in the constructor’s prototype, and the instanceof operator works just as before. Repeating the sub-classing example using the new syntax:

class A                             // Define super class
{
    constructor()
    {
        this.x = 1;
    }

    DoIt()                          // Define Method
    {
        this.x += 1;
    }
}

class B extends A                   // Define sub-class
{
    constructor()
    {
        super();                    // Call super-class constructor (required)
        this.y = 2;
    }

    DoIt()                          // Define Method
    {
        super.DoIt();               // Call super-class method (if desired)
        this.y += 1;
    }
}

b = new B;

document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>');
document.write((typeof B) + '<BR/>');
b.DoIt();
document.write(b.x + ', ' + b.y);
true, true
function
2, 3
b
x2
y3
B.prototype
constructorB
DoItfunction ...
A.prototype
(constructor)A
(DoIt)function ...
Object.prototype
(constructor)Object

Note that a class really is a function, and that the resulting objects are identical to those in the Object.create example above. But with this syntax, the call to the super-class constructor is no longer optional; the constructor of a sub-class must call super() before it can use this.

TypeScript

TypeScript adds type declarations to JavaScript, and is compiled into ordinary JavaScript by removing them. Since a browser cannot run TypeScript directly, the output below is from the JavaScript this example compiles to:

class Counter
{
    private count: number = 0;      // Private (to the compiler)

    Add(n: number): void
    {
        this.count += n;
    }

    GetCount(): number
    {
        return this.count;
    }
}

let c = new Counter;

c.Add(2);
c.Add(3);
document.write(String(c.GetCount()));
// document.write(c.count);       // Error: 'count' is private
5
c
count5
Counter.prototype
constructorCounter
Addfunction ...
GetCountfunction ...
Object.prototype
(constructor)Object

The compiler will not allow code outside the class to use count, but once compiled, it is an ordinary property of the object.

Private Members

Finally, JavaScript now supports true private members, whose names begin with # (standardized in 2022). Unlike TypeScript’s private modifier, these are enforced when the code runs. And unlike the private member paradigm described above, the methods are stored in the prototype and shared by every instance of the class, rather than copied into each one. Repeating the private member example:

class A
{
    #x = 7;

    GetX() { return this.#x; }
    SetX(xT) { this.#x = xT; }
}

obj = new A;
obj2 = new A;
document.write(obj.GetX() + ' ' + obj2.GetX());
obj.SetX(14);
document.write(' ' + obj.GetX() + ' ' + obj2.GetX());
7 7 14 7
obj
A.prototype
constructorA
GetXfunction ...
SetXfunction ...
Object.prototype
(constructor)Object
obj2
A.prototype
constructorA
GetXfunction ...
SetXfunction ...
Object.prototype
(constructor)Object

The private member #x does not appear in the object at all: it can only be used by code inside the class.