HomeJAVASCRIPTHow does Object.create() work?

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.

Share:ย 

No comments yet! You be the first to comment.

Leave a Reply

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