Main Page

Methods of inheritance

Although ECMAScript doesn’t strictly define abstract classes as some other languages do, it sometimes
creates certain base classes that aren’t supposed to be used. Usually these are simply documented as
abstract.
The subclasses you create inherit all properties and methods from the superclass, including the construc-
tor and method implementations. Remember, all the properties and methods are public, so subclasses
may access these directly. Subclasses may add new properties and methods not present in the superclass
or override properties and methods of the superclass with new implementations.
Methods of inheritance
As usual with ECMAScript, you have more than one way to implement inheritance. This is because
inheritance in JavaScript isn’t explicit; it’s emulated. This means that the interpreter doesn’t handle all
the inheritance details. It is up to you, as the developer, to handle inheritance in a way that is most
appropriate for your situation.
Object masquerading
Object masquerading was never intended when the original ECMAScript was conceived. Instead, it
evolved as developers began to understand exactly how functions worked and, specifically, how to use
the
this
keyword in the context of functions.
The reasoning goes like this: A constructor assigns all properties and methods (with the Constructor
Paradigm of class declaration) using the
this
keyword. Because a constructor is just a function, you can
make the constructor of
ClassA
into a method of
ClassB
and call it.
ClassB
then receives the properties
and methods defined in
ClassA
’s constructor. For example,
ClassA
and
ClassB
are defined in this way:
function ClassA(sColor) {
this.color = sColor;
this.sayColor = function () {
alert(this.color);
};
}
function ClassB(sColor) {
}
As you remember, the
this
keyword references the currently created object in a constructor; in a method,
however,
this
points to the owning object. The theory is that treating
ClassA
as a regular function instead
of as a constructor establishes a type of inheritance. This can be done in the constructor
ClassB
like so:
function ClassB(sColor) {
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
}
In this code, the method named
newMethod
is assigned to
ClassA
(remember, the name of a function is
just a pointer to it). Then, the method is called, passing the
color
argument from the
ClassB
construc-
tor. The final line of code deletes the reference to
ClassA
so that it cannot be called later on.
105
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 105


JavaScript EditorFree JavaScript Editor     Ajax Editor


©