Object.create Polyfill
Implement Object.myCreate(proto, propertiesObject).
Requirements:
protomust be an object, function, or null — throwTypeErrorotherwise- Return a new object whose
[[Prototype]]isproto - If
propertiesObjectis provided, apply it viaObject.defineProperties - Use the empty-constructor trick (the expected interview answer)
Examples
const animal = { speak() { return 'roar'; } };
const lion = Object.myCreate(animal);
console.log(lion.speak());
console.log(Object.getPrototypeOf(lion) === animal);roar
trueNotes
- The empty-constructor trick: `function F() {}; F.prototype = proto; return new F()`
- Cannot produce true null-prototype objects — mention this limitation in an interview
Hints
Editorial: Object.create Polyfill
Implementing Object.create from scratch
Object.create makes a new object whose [[Prototype]] is set to the argument you pass in, plus optional property descriptors as a second argument.
What the interviewer checks
- Do you know the classic empty-constructor trick to set the prototype?
- Do you handle the optional
propertiesObjectargument?
Implementation
Object.myCreate = function (proto, propertiesObject) { if (typeof proto !== "object" && typeof proto !== "function" && proto !== null) { throw new TypeError("Object prototype may only be an Object or null"); } function F() {} F.prototype = proto; const obj = new F(); if (propertiesObject !== undefined) { Object.defineProperties(obj, propertiesObject); } return obj; };
The empty-constructor trick explained
When you call new F(), JavaScript creates a new object and sets its [[Prototype]] to F.prototype. By assigning F.prototype = proto before new F(), you control what the new object inherits:
const animal = { speak() { return "roar"; } }; function F() {} F.prototype = animal; const lion = new F(); lion.speak(); // "roar" — inherited Object.getPrototypeOf(lion) === animal; // true
Using propertiesObject
The second argument mirrors Object.defineProperties — each key is a property descriptor:
const obj = Object.myCreate(animal, { name: { value: "Leo", writable: true, enumerable: true, configurable: true } }); obj.name; // "Leo"
The null-prototype caveat
The empty-constructor trick cannot produce a true null-prototype object. new F() always links to something because F.prototype = null makes the engine fall back to Object.prototype.
A spec-accurate implementation would use Object.setPrototypeOf:
// For null prototype only: const obj = {}; Object.setPrototypeOf(obj, null);
In an interview, mention this limitation and say the F trick covers all non-null prototypes, which is the expected answer.
Edge cases to mention
protomust be an object, function, ornull— other primitives throwproto = nullcreates an object with no prototype (pure dictionary)propertiesObjectuses full property descriptors, not simple values