Main Page

zInherit

the limit in an effort to create other ways of implementing inheritance. This section examines some of the
alternatives to the standard ECMAScript inheritance paradigms.
zInherit
Prototype chaining essentially copies all methods from an object to a class’s
prototype
object. But
what if there were a different way to accomplish this? There is. Using the zInherit library (available at
http://www.nczonline.net/downloads
), it’s possible to accomplish method inheritance without
using prototype chaining. This small library supports all modern browsers (Mozilla, IE, Opera, Safari)
as well as some older browsers (Netscape 4.x, IE/Mac).
In order to use the zInherit library, you must include zinherit.js using the
<script/>
tag. Chapter 5,
“JavaScript in the Browser,” discusses including external JavaScript files in detail.
The zInherit library adds two methods to the
Object
class:
inheritFrom()
and
instanceOf()
. As
you may have guessed, the
inheritFrom()
method does the heavy lifting, copying the methods from
a given class. The following line uses prototype chaining to inherit methods from
ClassA
to
ClassB
:
ClassB.prototype = new ClassA();
This line can be replaced with the following:
ClassB.prototype.inheritFrom(ClassA);
The
inheritFrom()
method accepts one argument, which is the class from which to copy the methods.
Note that, as opposed to prototype chaining, this paradigm doesn’t actually create a new instance of the
class to inherit from, making it a little safer and freeing the developer from worrying about the construc-
tor arguments.
The
instanceOf()
method is a replacement for the
instanceof
operator. Because this paradigm
doesn’t use prototype chaining at all, this line of code won’t work:
ClassB instanceof ClassA
The
instanceOf()
method makes up for this loss, working with
inheritFrom()
to keep track of all
superclasses:
ClassB.instanceOf(ClassA);
Polygons revisited
The entire polygon example can be rewritten using the zInherit library by replacing just two lines
(highlighted):
The
inheritFrom()
method call must be used exactly where the prototype assign-
ment normally occurs in order to ensure proper inheritance.
116
Chapter 4
07_579088 ch04.qxd 3/28/05 11:36 AM Page 116


JavaScript EditorFree JavaScript Editor     Ajax Editor


©