HTML and CSS Reference
In-Depth Information
assert(circle.isPrototypeOf(sphere));
assertEquals(circle, Object.getPrototypeOf(sphere));
}
You might recognize
Object.create
from Section 7.5.1,
The
Object.
create
Method,
in Chapter 7,
Objects and Prototypal Inheritance,
in which we did
in fact implement exactly such a method. The ES5
Object.create
does us one
better—it can also add properties to the newly created object, as seen in Listing 8.8.
Listing 8.8
Create an object with properties
"test Object.create with properties": function () {
var circle = { /* ... */ };
var sphere = Object.create(circle, {
radius: {
value: 3,
writable: false,
configurable: false,
enumerable: true
}
});
assertEquals(3, sphere.radius);
}
As you might have guessed,
Object.create
sets the properties using
Ob-
ject.defineProperties
(which in turn uses
Object.defineProperty
).
Its implementation could possibly look like Listing 8.9.
Listing 8.9
Possible
Object.create
implementation
if (!Object.create && Object.defineProperties) {
Object.create = function (object, properties) {
function F () {}
F.prototype = object;
var obj = new F();
if (typeof properties != "undefined") {
Object.defineProperties(obj, properties);
}
return obj;
};
}