Prototypes

In JavaScript, prototypes are the mechanism by which objects inherit features from one another. Every object has an internal link to another object called its prototype.

Illustration of prototypes
Illustration of prototypes

💡 Prototype Basics

When accessing a property or method on an object, JavaScript looks first at the object itself. If it doesn't find it, it follows the object's prototype chain until it finds the property or reaches null.

The prototype chain allows objects to share methods and properties efficiently without duplicating them.

Prototype Chain Lookup
StepAction
1Look for property on the object itself
2If not found, look on the object's prototype
3Repeat up the prototype chain
4Stop when property is found or prototype is null

All functions in JavaScript have a prototype property that is used when creating new objects with new. This prototype object becomes the prototype of the created object.

📌 Deep Dive: Using Prototypes to Share Methods

JAVASCRIPT
function Person(name) {
  this.name = name;
}

// Add method to Person prototype
Person.prototype.greet = function() {
  return `Hello, my name is ${this.name}`;
};

const alice = new Person('Alice');
console.log(alice.greet()); // Hello, my name is Alice
Output
Hello, my name is Alice

💡 Why Use Prototypes?

Methods added to the prototype are shared across all instances, reducing memory usage compared to defining methods inside the constructor function.

Objects created with object literals inherit from Object.prototype by default:

📌 Deep Dive: Prototype of Object Literals

JAVASCRIPT
const obj = { a: 1 };
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
console.log(obj.toString()); // [object Object]
Output
true
[object Object]

⚠️ Important

Modifying built-in prototypes like Array.prototype or Object.prototype can cause unexpected behavior and is generally discouraged.

You can examine an object's prototype using Object.getPrototypeOf(obj) or the deprecated __proto__ property (avoid using __proto__ in production).

Prototype Access Methods
MethodDescription
Object.getPrototypeOf(obj)Returns the prototype of the specified object
obj.__proto__Returns or sets the prototype of the object (deprecated)

Understanding prototypes is key to mastering inheritance and object behavior in JavaScript.