With Object.create(), the prototype of an object can be set directly; thus you can define an inheritance chain, where each object refers to a parent object as prototype, without creating function constructors to use as classes, or anonymous functions to simulate the mechanism.
You can also set additional properties at the creation of objects, and these properties can be decorated with metadata such as enumerable, writable, and deletable; the metadata prevents the deletion or modification of a property, and tells the browser which properties should be listed with for..in.
I told you this was bleeding edge! According to Mozilla,these are the browsers versions that support Object.create() in its full form, and with its companions:
- Internet Explorer 9
- Firefox 4
- Chrome 5
- No version of Opera.
- Safari 5
- Object.defineProperty(object, propertyName, descriptor) lets you add a property to an object after creation.
- Object.seal(object) prevents other code from deleting or adding properties: attempts to do so will be ignored (without raising errors). Writable properties values can be changed.
- Object.freeze(object) is the same as Object.seal() but also does not allow even the modification of existing properties.
Let's dive into some code
Here's a code sample, in the form of a test case for jsTestDriver, which exercises Object.create() and the other handy functions I cited earlier. You see we can manipulate objects and their prototype chains without defining a single class like in the classic inheritance examples.