Prototype Basics

const obj = {};
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
console.log(obj.__proto__ === Object.prototype); // true

Prototype Chain Visualization

When an object is created using a constructor function, it follows a prototype chain structure:

person (instance)
 |
 |  __proto__
 v
Person.prototype
 |
 |  __proto__
 v
Object.prototype
 |
 |  __proto__
 v
null

This means:

Prototypal Inheritance

There are two primary ways to implement prototypal inheritance in JavaScript: Constructor functions with prototype and the Object.create() approach.

Constructor Function + Prototype

function Animal(name: string) {
  this.name = name;
}
Animal.prototype.speak = function () {
  return `${this.name} makes a noise`;
};

const dog = new Animal("Dog");
console.log(dog.speak()); // Dog makes a noise

Object.create() Approach