Sometimes we want to augment a method of a base class rather than
replace it. This is easily accomplished in Java using the
super
keyword. For example, if we have a Button
widget with a draw method, and we extend that creating a
BorderButton widget, we might want to use Button's draw
method to draw the button and then draw a border around it.
To do this, BorderButton.draw
could call
super.draw()
and the compiler would call the
draw method of the closest ancestor which in this case would
be Button.draw
.
JavaScript does not have a super
keyword, but we
can use features of the language to accomplish the same goal.
Each function is passed an object called arguments
which includes all arguments passed to this function. It also
includes the function itself as the callee
.
Since a function is an object in JavaScript, we can attach
useful information to it such as a reference to a function
we are overriding. To take advantage of this information,
we will add a method called inherited
to the
prototype of XObject.
01: inherited: function(args) {02: var f = args.callee._inherited;03: if ( f ) {
04: f.apply(this,args);
05: }06: else {
07: console.error(this.className +
08: " does not inherit the method " + args.callee._name);
09: }10: }
Next we will see how the _inherited and _name properties are attached to methods.