HTML and CSS Reference
In-Depth Information
The drawback of this solution is its verbosity; The call to
Circle.
prototype.area
is long and couples
Sphere
very tightly to
Circle
. To miti-
gate this, Listing 7.33 makes the
inherit
function set up a “super” link for us.
Listing 7.33
Expecting the
_
super
link to refer to the prototype
"test should set up link to super": function () {
var SubFn = function () {};
var SuperFn = function () {};
SubFn.inherit(SuperFn);
assertEquals(SuperFn.prototype, SubFn.prototype._super);
}
Note the leading underscore. ECMA-262 defines
super
as a reserved word
intended for future use, so we best not use it. The implementation in Listing 7.34
is still straightforward.
Listing 7.34
Implementing a link to the prototype
if (!Function.prototype.inherit) {
(function () {
function F() {}
Function.prototype.inherit = function (superFn) {
F.prototype = superFn.prototype;
this.prototype = new F();
this.prototype.constructor = this;
this.prototype._super = superFn.prototype;
};
}());
}
Using this new property, Listing 7.35 simplifies
Sphere.prototype.area
.
Listing 7.35
Calling a method on the prototype chain
Sphere.prototype.area = function () {
return 4 * this._super.area.call(this);
};
7.3.3.1 The
_
super
Method
Although I would definitely not recommend it, someone serious about emulating
classical inheritance in JavaScript would probably prefer
_
super
to be a method