HTML and CSS Reference
In-Depth Information
Listing 7.28 Implementing inherit
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 implementation uses the same intermediate constructor for all calls, only
assigning the prototype for each call. Using this new function we can clean up our
circles and spheres, as seen in Listing 7.29.
Listing 7.29 Making Sphere inherit from Circle with inherit
function Sphere (radius) {
this.radius = radius;
More or less all the major JavaScript libraries ship with a variant of the inherit
function, usually under the name extend . I've named it inherit in order to avoid
confusion when we turn our attention to another extend method later in this
7.3.2 Accessing [[Prototype]]
The inherit function we just wrote makes it possible to easily create object hierarchies
using constructors. Still, comparing the Circle and Sphere constructors tells
us something isn't quite right—they both perform the same initialization of the
radius property. The inheritance we've set up exists on the object level through
the prototype chain, the constructors are not linked in the same way a class and a
subclass are linked in a classical language. In particular, JavaScript has no super
to directly refer to properties on objects from which an object inherits. In fact,
ECMA-262 3rd edition provides no way at all to access the internal [[Prototype]]
property of an object.
Even though there is no standardized way of accessing the [[Prototype]] of
an object, some implementations provide a non-standard __ proto __ property
Search WWH ::

Custom Search