Object.create()

Object.create() is a powerful JavaScript method used to create a new object with a specified prototype object and optional properties. It allows you to set up prototype-based inheritance explicitly.

Illustration of object_create
Illustration of object_create

💡 Why use Object.create()?

It helps create objects that inherit directly from another object, providing a clear and flexible way to set the prototype chain without using constructor functions or classes.

Basic Syntax

Object.create(proto, propertiesObject)

  • proto: The object which should be the prototype of the newly created object.
  • propertiesObject (optional): An object specifying property descriptors (like value, writable, enumerable, etc.).

How it works

The new object inherits all properties and methods from the proto object through the prototype chain.

📌 Deep Dive: Creating an object with a prototype

JAVASCRIPT
const person = {
  greet() {
    return `Hello, I am ${this.name}`;
  }
};

const alice = Object.create(person);
alice.name = "Alice";

console.log(alice.greet()); // Hello, I am Alice
Output
Hello, I am Alice

Setting properties on the new object

You can define properties with descriptors when creating the object:

📌 Deep Dive: Defining properties with descriptors

JAVASCRIPT
const animal = {
  speak() {
    return `${this.sound}!`;
  }
};

const dog = Object.create(animal, {
  sound: {
    value: "Woof",
    writable: true,
    enumerable: true,
    configurable: true
  }
});

console.log(dog.speak()); // Woof
dog.sound = "Bark";
console.log(dog.speak()); // Bark
Output
Woof
Bark

⚠️ Important:

If the first argument to Object.create() is null, the created object will have no prototype at all (no inherited properties or methods).

Comparison: Object.create() vs Object Literals
FeatureObject.create()Object Literal
Prototype controlExplicitly sets prototypeDefaults to Object.prototype
InheritanceAllows inheritance from any objectInherits from Object.prototype
Property descriptorsSupports property descriptors on creationUses default property descriptors

💡 Summary

  • Object.create() creates a new object with the specified prototype.
  • It allows setting properties with fine-grained control via descriptors.
  • It's a clean way to implement prototypal inheritance.