HTML and CSS Reference
In-Depth Information
Whenever someone forgets the
new
operator when calling the constructor,
this
will refer to the global object rather than a newly created object. By using
the
instanceof
operator, we're able to catch this, and can explicitly call the
constructor over again with the same arguments and return the new object.
ECMA-262 defines the behavior for all the native constructors when used as
functions. The result of calling a constructor as a function often has the same effect
as our implementation aboveāa new object is created as if the function was actually
called with the
new
operator.
Assuming that calling a constructor without
new
is usually a typo, you may
want to discourage using constructors as functions. Throwing an error rather than
sweeping the error under the rug will probably ensure a more consistent code base
in the long run.
Equipped with our understanding of constructors and their prototype properties,
we can now create arbitrary hierarchies of objects, in much the same way one
would create class hierarchies in a classical language. We will do this with
Sphere
,
a constructor whose
prototype
property inherits from
Circle.prototype
rather than
Object.prototype
.
We need
Sphere.prototype
to refer to an object whose internal [[Pro-
totype]] is
Circle.prototype
. In other words, we need a circle object to set
up this link. Unfortunately, this process is not straightforward; In order to create a
circle object we need to invoke the
Circle
constructor. However, the constructor
may provide our prototype object with unwanted state, and it may even fail in the
absence of input arguments. To circumvent this potential problem, Listing 7.25 uses
an intermediate constructor that borrows
Circle.prototype
.
Listing 7.25
Deeper inheritance
function Sphere(radius) {
this.radius = radius;
}
Sphere.prototype = (function () {
function F() {};
F.prototype = Circle.prototype;
return new F();
}());