Table of contents
- 1. Summary
- 2. Syntax
- 3. Parameters
- 4. Description
- 5. Examples
- 6. Cross-browser compatibility
- 6.1. Polyfill
- 7. See also
Summary
Creates a new object with the specified prototype object and properties.
Method of Object | |
|---|---|
| Implemented in | JavaScript 1.8.5 |
| ECMAScript Edition | ECMAScript 5th Edition |
Syntax
Object.create(proto [, propertiesObject ])
Parameters
- proto
- The object which should be the prototype of the newly-created object.
- propertiesObject
- If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names.
Description
Throws a TypeError exception if the proto parameter isn't null or an object.
Examples
var o;
// create an object with null as prototype
o = Object.create(null);
o = {};
// is equivalent to:
o = Object.create(Object.prototype);
function Constructor(){}
o = new Constructor();
// is equivalent to:
o = Object.create(Constructor.prototype);
// Of course, if there is actual initialization code in the Constructor function, the Object.create cannot reflect it
// create a new object whose prototype is a new, empty object
// and a adding single property 'p', with value 42
o = Object.create({}, { p: { value: 42 } })
// by default properties ARE NOT writable, enumerable or configurable:
o.p = 24
o.p
//42
o.q = 12
for (var prop in o) {
console.log(prop)
}
//"q"
delete o.p
//false
//to specify an ES3 property
o2 = Object.create({}, { p: { value: 42, writable: true, enumerable: true, configurable: true } });
Cross-browser compatibility
Based on Kangax's compat table.
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 5 | 4 (2.0) | 9 | -- | 5 |
| Feature | Firefox Mobile (Gecko) | Android | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | ? | ? | ? | ? | ? |
Polyfill
if (!Object.create) {
Object.create = function (o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
This polyfill covers the main use case which is creating a new object for which the prototype has been chosen but doesn't take the second argument into account.
See also
Object.defineProperty- Object.defineProperties
- Object.prototype.isPrototypeOf
- John Resig's post on getPrototypeOf