HTML and CSS Reference
In-Depth Information
// Don't forget the constructor - else it will resolve as
// Circle through the prototype chain
Sphere.prototype.constructor = Sphere;
Now we can create spheres that inherit from circles, as shown by the test in
Listing 7.26.
Listing 7.26 Testing the new Sphere constructor
"test spheres are circles in 3D": function () {
var radius = 6;
var sphere = new Sphere(radius);
assertTrue(sphere instanceof Sphere);
assertTrue(sphere instanceof Circle);
assertTrue(sphere instanceof Object);
assertEquals(12, sphere.diameter());
7.3.1 The Inherit Function
In Listing 7.25 we extended the Sphere constructor with the Circle construc-
tor by linking their prototypes together, causing sphere objects to inherit from
Circle.prototype . The solution is fairly obscure, especially when compared
with inheritance in other languages. Unfortunately, JavaScript does not offer any
abstractions over this concept, but we are free to implement our own. Listing 7.27
shows a test for what such an abstraction might look like.
Listing 7.27 Specification for inherit
TestCase("FunctionInheritTest", {
"test should link prototypes": function () {
var SubFn = function () {};
var SuperFn = function () {};
assertTrue(new SubFn() instanceof SuperFn);
We already implemented this feature in Listing 7.25, so we only need to move
it into a separate function. Listing 7.28 shows the extracted function.
Search WWH ::

Custom Search