Main Page

Hybrid method

ClassB.prototype.name = “”;
ClassB.prototype.sayName = function () {
alert(this.name);
};
You can test this code by running the following example:
var objA = new ClassA();
var objB = new ClassB();
objA.color = “red”;
objB.color = “blue”;
objB.name = “Nicholas”;
objA.sayColor(); //outputs “red”
objB.sayColor(); //outputs “blue”
objB.sayName(); //outputs “Nicholas”
As a bonus, the
instanceof
operator works in a rather unique way in prototype chaining. For all
instances of
ClassB
,
instanceof
returns
true
for both
ClassA
and
ClassB
. For example:
var objB = new ClassB();
alert(objB instanceof ClassA); //outputs “true”;
alert(objB instanceof ClassB); //outputs “true”
In the loosely typed world of ECMAScript, this can be an incredibly useful tool, one that is not available
when you use object masquerading.
The downside to prototype chaining is that it has no support for multiple inheritance. Remember, proto-
type chaining involves overwriting the prototype property of the class with another type of object.
Hybrid method
You may have noticed that this method of inheritance uses the constructor paradigm to define classes
without any use of prototyping. The main problem with object masquerading is that you must use the
constructor paradigm, which (as you learned in the last chapter) is not optimal. But if you go with proto-
type chaining, you lose the capability to have constructors with arguments. What’s a developer to do?
The answer is simple: Use both.
In the previous chapter, you learned that the best way to create classes is to use the constructor paradigm
to define the properties and to use the prototype paradigm to define the methods. The same goes for
inheritance; you use object masquerading to inherit properties from the constructor and prototype chain-
ing to inherit methods from the
prototype
object. Take a look at the previous example rewritten using
both methods of inheritance:
function ClassA(sColor) {
this.color = sColor;
}
ClassA.prototype.sayColor = function () {
alert(this.color);
};
function ClassB(sColor, sName) {
110
Chapter 4
07_579088 ch04.qxd 3/28/05 11:36 AM Page 110


JavaScript EditorFree JavaScript Editor     Ajax Editor


©