| home / programming / javascript / professional / chap3 / 3 |
[previous] [next] |
|
Professional JavaScriptInheritance via a Shared Class ObjectThe simplest form of inheritance in JavaScript is for the object instance for the derived class to collect the information it inherits from the class definition object for its base class. Therefore this is a case of mixing up instance and class objects.
This example has two object constructors: the two functions. Since functions are objects in JavaScript, there are two new objects as well. There is also a third new object. It has been added to the Rectangle function object's prototype chain in the last line, and that is the only place it is accessible. That object can be thought of as a class definition object, because it is only really used at object creation time, and there is only ever one of it. To create a new Rectangle, use this code:
Afterwards the object's properties are:
The benefits of this approach are:
However, this approach does have drawbacks. The problems mostly revolve around the fact that there is only one prototype chain for the Rectangle constructor, and it is shared between all Rectangle objects that are created. So any Rectangle object that modifies properties of the base class changes them for all Rectangle objects.
You can work around the first problem by overriding all the base class objects properties in the derived instance object constructor (Rectangle). However, if you do that, overriding everything, one wonders why bother use inheritance at all – you might as well just have a separate object type. Sometimes you do want properties in the base class to be updated by every derived instance ('static class variables'). Here's an example:
Every object contributes something to the shared property. In the example above, this property is a total of the objects currently existing (this simple example doesn't correctly decrease the total if objects go away). Finally, if you can avoid changing any state in the base class object, then the approach we've outlined here can still be quite useful. You could put a store of constant data and methods in it that will be usable by all derived instance objects. The methods in the base class object can refer to properties in derived instances as well. Here's an example:
Notice how in this example the base class object uses, but may never define the value property. In that case, the derived instance object's value property will be doubled. The 'if' condition in the base class object is only true if the Base() function is used as a simple constructor, not when inheritance is at work. For C++ and Java experts: this mechanism works well for abstract base classes. |
| home / programming / javascript / professional / chap3 / 3 |
[previous] [next] |
Created: February 12, 2001
Revised: February 12, 2001