JAVASCRIPT

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 in Object.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

  1. Object.create() is used for prototypal inheritance without using classes or constructor functions.
  2. The new object’s [[Prototype]] (or __proto__) is set to the object you pass.
  3. Unlike class or constructor functions, it doesn’t run any initialization logic (like new would).
  4. If you pass null as prototype, the created object will not inherit from Object.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.

Leave a Reply

Your email address will not be published. Required fields are marked *