Object.create lets you make a new object that uses another object as its base. This helps you share properties and methods easily.
0
0
Object.create usage in Javascript
Introduction
When you want to make a new object that shares behavior with an existing object.
When you want to create objects without repeating the same properties or methods.
When you want to set up a simple inheritance between objects.
When you want to create an object with a specific prototype.
When you want to avoid using classes but still share features between objects.
Syntax
Javascript
const newObject = Object.create(prototypeObject, propertiesObject);
prototypeObject is the object you want to use as the base (prototype).
propertiesObject is optional and lets you add new properties with descriptors.
Examples
Creates
dog that uses animal as its base. Calling dog.speak() runs the method from animal.Javascript
const animal = { speak() { console.log('Animal sound'); } }; const dog = Object.create(animal); dog.speak();
Creates
john with person as prototype and adds a name property.Javascript
const person = { greet() { console.log(`Hello, my name is ${this.name}`); } }; const john = Object.create(person, { name: { value: 'John', writable: true, enumerable: true, configurable: true } }); john.greet();
Sample Program
This program creates a car object that inherits the start method from vehicle. Then it adds a new property wheels to car.
Javascript
const vehicle = { start() { console.log('Vehicle started'); } }; const car = Object.create(vehicle); car.start(); car.wheels = 4; console.log(`Car has ${car.wheels} wheels`);
OutputSuccess
Important Notes
Objects created with Object.create have their prototype set to the object passed as the first argument.
If you pass null as the prototype, the new object will not inherit anything.
Using Object.create is a simple way to do inheritance without classes.
Summary
Object.create makes a new object using another object as a base.
It helps share properties and methods without copying them.
You can add new properties while creating the object.