Q17: Implement a polyfill for Object.create().
Answer
Object.create() creates a new object with a specified prototype. Passing null creates an object with no prototype.
if (!Object.myCreate) {
Object.myCreate = function (prototype) {
if (
prototype !== null &&
typeof prototype !== "object" &&
typeof prototype !== "function"
) {
throw new TypeError("Prototype must be an object or null");
}
function TemporaryConstructor() {}
TemporaryConstructor.prototype = prototype;
const result = new TemporaryConstructor();
TemporaryConstructor.prototype = null;
return result;
};
}
const person = {
greet() {
return `Hello, ${this.name}`;
}
};
const user = Object.myCreate(person);
user.name = "Suriya";
console.log(user.greet());
// Hello, Suriya
console.log(Object.getPrototypeOf(user) === person);
// true
Explanation
The temporary constructor creates an object whose prototype is the specified object. The resulting object inherits properties from that prototype without copying them.
Important limitation
This classic technique does not fully reproduce all native behavior, including the optional property-descriptor argument and some legacy edge cases. It is useful for understanding prototype inheritance in interviews.
Key Takeaways
- Object.create establishes the prototype of a new object.
- Prototype inheritance is different from copying an object's properties.