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).
So, for example, we can create a new object and add several ad-hoc properties to it with the following code:
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.
For example, if we want to create an object, X, from constructor function B, whose prototype chain is: B.prototype, A.prototype, Object.prototype:
We would use the following code:
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.
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.
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.
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).
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:
Repeating the sub-classing example using this new paradigm:
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).
ECMA-262 (PDF) - ECMAScript Standard Documentation