العودة إلى الدورة

Understanding Prototypes (The Inheritance Chain)

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

76. Understanding Prototypes (The Inheritance Chain)

JavaScript is a prototype-based language. Classes (extends) and constructor functions are just ways to manage this underlying prototype system.

What is the Prototype?

Every object in JavaScript has an internal link to another object called its prototype. When you try to access a property or method on an object, JS first looks for it on the object itself. If it doesn't find it, it follows the internal link to the prototype object, and so on, up the chain until it reaches null.

Example: Array Prototype

When you create an array myArr = [], it doesn't physically contain the code for .push(), .pop(), or .map(). It links to Array.prototype.

javascript const arr = [1, 2];

// When we call .push(), JS checks: // 1. Does 'arr' have a push method? No. // 2. Does arr's prototype (Array.prototype) have a push method? Yes.

arr.push(3);

Benefits

  1. Memory Efficiency: Methods are stored only once on the prototype, not duplicated across every instance.
  2. Inheritance: Prototypes form the mechanism of inheritance in JS.