๐น What is Object.create()?
Object.create() is a built-in JavaScript method that creates a new object and sets its prototype to another object you specify.
Syntax:
Object.create(proto, [propertiesObject])
protoโ The object to be used as the prototype of the new object.propertiesObject(optional) โ An object containing property descriptors (like inObject.defineProperties()).
๐น Example 1: Basic usage
const animal = {
eats: true,
walk() {
console.log("Animal is walking");
}
};
// Create a new object with 'animal' as prototype
const dog = Object.create(animal);
dog.barks = true;
console.log(dog.eats); // true (inherited from animal)
dog.walk(); // "Animal is walking"
console.log(dog.barks); // true (own property)
โ
Here, dog doesnโt have eats directly, but since its prototype is animal, it inherits eats and walk().
๐น Example 2: With property descriptors
const person = {
isHuman: false,
};
const me = Object.create(person, {
name: {
value: "Himanshu",
writable: true,
enumerable: true,
},
age: {
value: 27,
writable: false,
}
});
console.log(me.name); // "Himanshu"
console.log(me.isHuman); // false (inherited)
๐น Key Points
Object.create()is used for prototypal inheritance without using classes or constructor functions.- The new objectโs
[[Prototype]](or__proto__) is set to the object you pass. - Unlike
classor constructor functions, it doesnโt run any initialization logic (likenewwould). - If you pass
nullas prototype, the created object will not inherit fromObject.prototype(useful for dictionaries).
๐น Example 3: Create object without prototype
const dict = Object.create(null);
dict.apple = "๐";
dict.orange = "๐";
console.log(dict.apple); // "๐"
console.log(dict.toString); // undefined (no Object prototype)
๐ In short:Object.create(proto) creates a new object that inherits from proto. Itโs a clean and flexible way to implement inheritance in JavaScript.
