Interview question
How does Object.create() work and how is it different from using 'new'? Object.create() कैसे काम करता है और 'new' से कैसे अलग है?
Answer
Object.create() creates a new object with a specified prototype directly, without invoking a constructor function - giving explicit control over the prototype link.
// Object.create with an explicit prototype object
const animal = {
eats: true,
walk() {
console.log(`${this.name} is walking`);
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
rabbit.jumps = true;
console.log(rabbit.eats); // true - inherited
rabbit.walk(); // Rabbit is walking
console.log(Object.getPrototypeOf(rabbit) === animal); // true
// Object.create(null) - object with NO prototype at all (not even Object.prototype)
const pureDict = Object.create(null);
pureDict.key = 'value';
console.log(pureDict.toString); // undefined - no inherited methods at all
// Useful for objects used purely as dictionaries/maps, avoiding prototype pollution
// Object.create with property descriptors (second argument)
const obj = Object.create(animal, {
name: { value: 'Bunny', writable: true, enumerable: true }
});
console.log(obj.name); // Bunny
// Comparison: using 'new' with a constructor function
function Animal(name) {
this.name = name;
}
Animal.prototype.eats = true;
const newAnimal = new Animal('Cat');
// 'new' does 4 things: 1) creates a new object, 2) sets its prototype to
// Animal.prototype, 3) calls Animal with 'this' bound to the new object,
// 4) returns the new object (unless the constructor returns its own object)
// Object.create is more direct - no constructor function/logic needed,
// just specify the prototype object explicitlyObject.create() specified prototype के साथ सीधे नया object बनाता है, constructor function invoke किए बिना - prototype link पर explicit control देता है।
const animal = {
eats: true,
walk() {
console.log(`${this.name} is walking`);
}
};
const rabbit = Object.create(animal);
rabbit.name = 'Rabbit';
rabbit.jumps = true;
console.log(rabbit.eats); // true - inherited
rabbit.walk(); // Rabbit is walking
console.log(Object.getPrototypeOf(rabbit) === animal); // true
// Object.create(null) - बिल्कुल prototype नहीं
const pureDict = Object.create(null);
pureDict.key = 'value';
console.log(pureDict.toString); // undefined - कोई inherited methods नहीं
// Property descriptors के साथ
const obj = Object.create(animal, {
name: { value: 'Bunny', writable: true, enumerable: true }
});
console.log(obj.name); // Bunny
// 'new' के साथ compare करना
function Animal(name) {
this.name = name;
}
Animal.prototype.eats = true;
const newAnimal = new Animal('Cat');
// 'new' चार काम करता है: 1) नया object बनाना, 2) prototype set करना,
// 3) constructor को call करना 'this' bind करके, 4) object return करनाWas this answer clear?