HTML and CSS Reference
In-Depth Information
7.5.1 The Object.create Method
In Section 7.3, Pseudo-classical Inheritance, we took a dive into JavaScript construc-
tors and saw how they allow for a pseudo-classical inheritance model. Unfortunately,
going too far down that road leads to complex solutions that suffer on the perfor-
mance side, as evidenced by our rough implementation of super . In this section,
as in the previous on functional inheritance, we'll focus solely on objects, bypassing
the constructors all together.
Returning to our previous example on circles and spheres, we used constructors
along with the inherit function to create a sphere object that inherited proper-
ties from Circle.prototype . The Object.create function takes an object
argument and returns a new object that inherits from it. No constructors involved,
only objects inheriting from other objects. Listing 7.47 describes the behavior with
a test.
Listing 7.47 Inheriting directly from objects
TestCase("ObjectCreateTest", {
"test sphere should inherit from circle":
function () {
var circle = {
radius: 6,
area: function () {
return this.radius * this.radius * Math.PI;
var sphere = Object.create(circle);
sphere.area = function () {
return 4 *;
assertEquals(452, Math.round(sphere.area()));
Here we expect the circle and sphere objects to behave as before, only
we use different means of creating them. We start out with a specific circle object.
Then we use Object.create to create a new object whose [[Prototype]] refers
to the old object, and we use this object as the sphere. The sphere object is then
modified to fit the behavior from the constructor example. Should we want new
Search WWH ::

Custom Search