HTML and CSS Reference
In-Depth Information
Circle.prototype.area = function () {
return this.radius * this.radius * Math.PI;
};
Listing 7.17 shows a simple test to verify that objects do indeed inherit the
methods.
Listing 7.17 Testing Circle.prototype.diameter
"test should inherit properties from Circle.prototype":
function () {
var circle = new Circle(6);
assertEquals(12, circle.diameter());
}
Repeating Circle.prototype quickly becomes cumbersome and expensive
(in terms of bytes to go over the wire) when adding more than a few properties to
the prototype. We can improve this pattern in a number of ways. Listing 7.18 shows
the shortest way—simply provide an object literal as the new prototype.
Listing 7.18 Assigning Circle.prototype
Circle.prototype = {
diameter: function () {
return this.radius * 2;
},
circumference: function () {
return this.diameter() * Math.PI;
},
area: function () {
return this.radius * this.radius * Math.PI;
}
};
Unfortunately, this breaks some of our previous tests. In particular, the assertion
in Listing 7.19 no longer holds.
Listing 7.19 Failing assertion on constructor equality
assertEquals(Circle, circle.constructor)
 
Search WWH ::




Custom Search