↑
Main Page
call() method
this.newMethod();
delete this.newMethod;
}
The one downside to this is that if
ClassX
and
ClassY
have a property or method with the same name,
ClassY
’s takes priority because it is inherited from last. Besides that minor issue, multiple inheritance
with object masquerading is a breeze.
Because this method of inheritance caught on, the third edition of ECMAScript includes two new meth-
ods of the
Function
object:
call()
and
apply()
.
The call() method
The
call()
method is the method most similar to the classic object-masquerading method. Its first
argument is the object to be used for
this
. All other arguments are passed directly to the function itself.
For example:
function sayColor(sPrefix, sSuffix) {
alert(sPrefix + this.color + sSuffix);
};
var obj = new Object();
obj.color = “red”;
//outputs “The color is red, a very nice color indeed. “
sayColor.call(obj, “The color is “, “, a very nice color indeed. “);
In this example, the function
sayColor()
is defined outside of an object, and it references the
this
key-
word even though it is not attached to any object. The object
obj
is given a
color
property equal to
“red”
. When
call()
is, well, called, the first argument is
obj
, which indicates that the
this
keyword
in
sayColor()
should be assigned the value of
obj
. The second and third arguments are strings. They
are matched up with the
prefix
and
suffix
arguments of
sayColor()
, resulting in the message
“The
color is red, a very nice color indeed.”
being displayed.
To use this with the object masquerading method of inheritance, just replace the three lines that assign,
call, and delete the new method:
function ClassB(sColor, sName) {
//this.newMethod = ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this, sColor);
this.name = sName;
this.sayName = function () {
alert(this.name);
};
}
Here, you want the
this
keyword in
ClassA
to be equal to the newly created
ClassB
object, so this is
passed in as the first argument. The second argument is the
color
argument, the only one for either
class.
107
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 107
Free JavaScript Editor
Ajax Editor
©
→