JavaScriptPrototypes & Inheritance

JavaScript Prototypes & Inheritance

JavaScript uses prototypal inheritance, which is fundamentally different from classical inheritance found in languages like Java or C++.

The Prototype Chain

Every JavaScript object has a prototype. When you try to access a property that doesn't exist on an object, JavaScript looks up the prototype chain.

const animal = {
  speak() {
    console.log(\\${this.name} makes a sound.\);
  }
};

const dog = Object.create(animal); dog.name = 'Rex'; dog.speak(); // Rex makes a sound.

Constructor Functions

function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.greet = function() { return \Hi, I'm \${this.name}\; };

const john = new Person('John', 30); console.log(john.greet()); // Hi, I'm John

ES6 Classes

Classes in JavaScript are syntactic sugar over prototypes:

class Animal {
  constructor(name) {
    this.name = name;
  }

speak() { console.log(\\${this.name} makes a sound.\); } }

class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; }

speak() { console.log(\\${this.name} barks.\); } }

const rex = new Dog('Rex', 'German Shepherd'); rex.speak(); // Rex barks.

Best Practices

  • Prefer composition over inheritance
  • Use Object.create() for simple prototypal inheritance
  • Use ES6 classes for more complex hierarchies