All questions

Object.create

Premium

Object.create

Object.create makes a brand-new object with a prototype you choose — the most direct way to set up inheritance in JavaScript. Give it an object and the new object inherits from it; give it null and you get a truly empty object with no prototype at all (not even Object.prototype).

Implement objectCreate(proto, propertiesObject). Return a new object whose [[Prototype]] is proto. If propertiesObject is provided, define those own properties from their descriptors, like Object.defineProperties. Throw a TypeError if proto is a non-null primitive.

Signature

function objectCreate(proto, propertiesObject) {
  // new object inheriting from `proto`, with optional own descriptor props.
}

Examples

const animal = { speak() { return 'noise'; } };
const dog = objectCreate(animal);
dog.speak();                     // 'noise' — inherited
Object.getPrototypeOf(dog) === animal; // true
const bare = objectCreate(null);         // no prototype at all
bare.toString;                            // undefined
objectCreate(null, { x: { value: 1, enumerable: true } }); // { x: 1 }

Notes

  • Sets the prototypeObject.getPrototypeOf(result) is exactly proto.
  • Inherits, doesn't copy — the new object has no own properties from proto; it looks them up the chain.
  • null prototype — a "dictionary" object with none of Object.prototype's methods (toString, hasOwnProperty, …).
  • DescriptorspropertiesObject maps names to descriptors (value/writable/enumerable/configurable, or get/set); apply them as own properties.
  • Invalid proto — a number, string, boolean, etc. throws a TypeError; only an object or null is allowed.
WE’RE LISTENING

Help make UIReady better

Found a bug or have an idea? Tell us about it.

Up to 3 files · 5 MiB each · JPG, PNG, WebP, MP4, WebM, MP3, M4A or WAV