0
0
JavascriptHow-ToBeginner · 3 min read

How to Create Object Using Object.create in JavaScript

Use Object.create(proto) to create a new object with proto as its prototype. This method lets you set the prototype of the new object directly, unlike using object literals or constructors.
📐

Syntax

The syntax for creating an object with a specific prototype is:

Object.create(proto, propertiesObject)

Here:

  • proto is the object to be used as the new object's prototype.
  • propertiesObject is optional and lets you add properties to the new object with descriptors.
javascript
const newObj = Object.create(proto, {
  property1: {
    value: 42,
    writable: true,
    enumerable: true,
    configurable: true
  }
});
💻

Example

This example shows how to create a new object with a prototype and access inherited properties.

javascript
const animal = {
  eats: true,
  walk() {
    return 'Animal walks';
  }
};

const rabbit = Object.create(animal);
rabbit.jumps = true;

console.log(rabbit.eats);       // true (inherited from animal)
console.log(rabbit.jumps);      // true (own property)
console.log(rabbit.walk());     // Animal walks (inherited method)
Output
true true Animal walks
⚠️

Common Pitfalls

Common mistakes include:

  • Passing null or a non-object as the prototype, which can cause errors.
  • Expecting Object.create to copy properties instead of setting the prototype.
  • Not understanding that properties on the prototype are shared by all objects created this way.
javascript
/* Wrong: expecting copy of properties */
const original = {a: 1};
const copy = Object.create(original);
copy.a = 2;
console.log(original.a); // 1, original is unchanged

/* Right: to copy properties, use spread or Object.assign */
const clone = {...original};
clone.a = 2;
console.log(original.a); // 1
console.log(clone.a);    // 2
Output
1 1 2
📊

Quick Reference

Tips for using Object.create:

  • Use it to set the prototype of a new object easily.
  • Pass null as prototype to create an object with no prototype.
  • Use the second argument to define properties with descriptors.
  • Remember it does not copy properties, only sets prototype.

Key Takeaways

Object.create(proto) creates a new object with proto as its prototype.
It does not copy properties, it links the prototype chain.
You can add properties with descriptors using the second argument.
Passing null creates an object with no prototype.
Inherited properties are accessible but shared among all objects with the same prototype.