Problem Statement
What does Object.create() do?
Explanation
Object.create creates a new object with the specified object as its prototype.
You pass the prototype object as the first argument. The new object will inherit from it.
Object.create allows creating objects without using constructor functions or classes.
It is the purest form of prototypal inheritance in JavaScript.
You can pass null to create an object with no prototype, useful for creating truly empty objects.
Object.create is commonly used in design patterns and frameworks.
Code Solution
SolutionRead Only
// Basic Object.create
const personProto = {
greet: function() {
console.log('Hello, ' + this.name);
}
};
const john = Object.create(personProto);
john.name = 'John';
john.greet(); // 'Hello, John'
// john inherits from personProto
console.log(Object.getPrototypeOf(john) === personProto); // true
// Create object with no prototype
const emptyObj = Object.create(null);
console.log(Object.getPrototypeOf(emptyObj)); // null
// No toString, hasOwnProperty, etc.
// Adding properties during creation
const jane = Object.create(personProto, {
name: {
value: 'Jane',
writable: true,
enumerable: true,
configurable: true
},
age: {
value: 25,
writable: true
}
});
jane.greet(); // 'Hello, Jane'
console.log(jane.age); // 25
// Inheritance pattern with Object.create
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
console.log(this.name + ' is eating');
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(this.name + ' says woof!');
};
const buddy = new Dog('Buddy', 'Golden Retriever');
buddy.eat(); // 'Buddy is eating'
buddy.bark(); // 'Buddy says woof!'
// Compare with direct assignment (wrong)
Dog.prototype = Animal.prototype; // Don't do this!
// This shares the same object, not creates inheritance