HTML and CSS Reference
In-Depth Information
spheres, we could simply create more objects like the one we already have, as seen in
Listing 7.48.
Listing 7.48
Creating more
sphere
objects
"test should create more spheres based on existing":
function () {
var circle = new Circle(6);
var sphere = Object.create(circle);
sphere.area = function () {
return 4 * circle.area.call(this);
};
var sphere2 = Object.create(sphere);
sphere2.radius = 10;
assertEquals(1257, Math.round(sphere2.area()));
}
The
Object.create
function in Listing 7.49 is simpler than the previous
Function.prototype.inherit
method because it only needs to create a
single object whose prototype is linked to the object argument.
Listing 7.49
Implementing
Object.create
if (!Object.create) {
(function () {
function F() {}
Object.create = function (object) {
F.prototype = object;
return new F();
};
}());
}
We create an intermediate constructor like before and assign the object argu-
ment to its prototype property. Finally we create a new object from the intermediate
constructor and return it. The new object will have an internal [[Prototype]] prop-
erty that references the original object, making it inherit directly from the object
argument. We could also update our
Function.prototype.inherit
func-
tion to use this method.
ES5 codifies the
Object.create
function, which “creates a new object with
a specified prototype”. Our implementation does not conform, because it does not