Main Page

Prototype chaining

case, you must create a separate array to place the arguments into the correct order. You could also use
the
call()
method.
Prototype chaining
The form of inheritance actually intended for use in ECMAScript is prototype chaining. The last chapter
introduced the prototype paradigm for defining classes. Prototype chaining builds off this paradigm to
accomplish inheritance in an interesting way.
In the last chapter, you learned that the
prototype
object is the template upon which an object is based
when instantiated. To summarize: Any properties or methods on the
prototype
object will be passed
on all instances of that class. Prototype chaining uses this functionality to accomplish inheritance.
If the classes from the previous example are redefined using the prototype paradigm, they become the
following:
function ClassA() {
}
ClassA.prototype.color = “red”;
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB() {
}
ClassB.prototype = new ClassA();
The magic in prototype chaining occurs in the highlighted previous line. Here, you are setting the
prototype
property of
ClassB
to be an instance of
ClassA
. This makes perfect sense because you want
all the properties and methods of
ClassA
, but you don’t want to have to assign each of them separately
to
ClassB
’s prototype property. What better way to do this than just to make the
prototype
into an
instance of
ClassA
?
Similar to object masquerading, all new properties and methods of the subclass must come after the
assignment of the
prototype
property because all methods assigned before will be deleted. Why?
Because the
prototype
property is being completely replaced with a new object; the original object to
which you would have added the methods is destroyed. So to add the name property and the
sayName()
method to
ClassB
, the code looks like this:
function ClassB() {
}
ClassB.prototype = new ClassA();
Note that no parameters are passed into the
ClassA
constructor call. This is standard
in prototype chaining. Be sure that your constructor functions properly without any
arguments.
109
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 109


JavaScript EditorFree JavaScript Editor     Ajax Editor


©