How does Object.create() work?
πΉ 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.
No comments yet! You be the first to comment.
