February 22, 2001 - Adding Methods and Properties on the Fly
February 22, 2001 Adding Methods and Properties on the Fly Tips: February 2001
Yehuda Shiran, Ph.D.
|
subClass()
. Here is an example:
function superClass() {
this.bye = superBye;
this.hello = superHello;
}
function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.bye = subBye;
}
The other way to inherit from a superclass is by protyping. Here is an example:
function superClass1() {
this.bye = superBye1;
this.hello = superHello1;
}
function subClass1() {
this.bye = subBye1;
}
subClass1.prototype = new superClass1;
It seems as if we have two 100%-equivalent ways to inherit methods and properties, but this is not accurate. Prototyping is better because it supports dynamic inheritance. You can define superclass methods and properties, after the constructor is done, and have the subclass object pick the new methods and properties. Here is an example that defines the blessyou()
functions:
function superClass1() {
this.bye = superBye1;
this.hello = superHello1;
}
function subClass1() {
this.bye = subBye1;
}
subClass1.prototype = new superClass1;
function superHello1() {
return "Hello from superClass";
}
function superBye1() {
return "Bye from superClass";
}
function subBye1() {
return "Bye from subClass";
}
var newClass1 = new subClass1();
superClass1.prototype.blessyou = superBlessyou;
function superBlessyou() {
return "Bless You from superClass";
}
function printSub1() {
alert(newClass1.bye());
alert(newClass1.hello());
alert(newClass1.blessyou());
}
Notice the three lines:
superClass1.prototype.blessyou = superBlessyou;
function superBlessyou() {
return "Bless You from superClass";
}
We define the function blessyou()
and then print it from the subclass object:
var newClass1 = new subClass1();
function printSub1() {
alert(newClass1.bye());
alert(newClass1.hello());
alert(newClass1.blessyou());
}