Skip to main content
TOPIC 9 OF 9 · 2 MIN READ

__proto__

`__proto__` is an internal property available on all objects in JavaScript. It is a reference to the prototype of the object. It provides access to the prototype chain, which is the mechanism JavaScript uses to inherit properties and methods.

Key concepts

__proto__

An internal property available on all objects in JavaScript. It is a reference to the prototype of the object (the value of `Object.getPrototypeOf(obj)`). It allows traversal of the prototype chain. It is a legacy feature but widely supported.

Step by step

Key Points:

  • `__proto__` points to the object's prototype (the value of `Object.getPrototypeOf(obj)`).
  • It allows traversal of the prototype chain.
  • It is a legacy feature but widely supported.

Differences Between prototype and __proto__:

prototype: Property of constructor functions that is shared by all instances. Exists only on functions (used for object creation). Use Case: Defines shared properties/methods for instances. __proto__: Property of an object pointing to its prototype. Exists on all objects. Use Case: Traversing or modifying the prototype chain.

Best Practices:

  • Direct manipulation of `__proto__` is not recommended for performance reasons.
  • Use modern methods like `Object.create()`, `Object.setPrototypeOf()`, and `Object.getPrototypeOf()` instead.

When to Use:

  • Use `Object.create()` to create new objects with a specific prototype.
  • Use `Object.setPrototypeOf()` and `Object.getPrototypeOf()` for managing prototype chains explicitly.
  • Avoid using `__proto__` in modern JavaScript code as it is considered a legacy feature.

Examples

__proto__ Example:

const person = { name: 'Alice' };
const proto = { greet: function () { console.log('Hello!'); } };

// Setting prototype using __proto__
person.__proto__ = proto;

person.greet(); // Hello!

Accessing Methods in the Prototype Chain:

const parent = { greet: function () { console.log('Hello from parent!'); } };
const child = { name: 'Alice' };

child.__proto__ = parent;

child.greet(); // Hello from parent!

Setting __proto__ Explicitly:

const animal = { eat: function () { console.log('Eating...'); } };
const dog = { bark: function () { console.log('Barking...'); } };

dog.__proto__ = animal;

dog.eat(); // Eating...
dog.bark(); // Barking...

Summary

`__proto__` is a legacy property for accessing an object's prototype. While widely supported, modern JavaScript code should use `Object.create()`, `Object.setPrototypeOf()`, and `Object.getPrototypeOf()` instead for better performance and maintainability.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus