Inheritance in JavaScript

Inheritance in JavaScript is more like a team where you delegate tasks that you cannot do it yourself, this is the reason this relationship model in JS is referred as Behaviour Delegation.

Meher Howji avatar image
··· Likes

JavaScript's prototypal system is inspired by the language Self. Self was the first one to implement the prototypal system. Lua, ActionScript, JScript, Cecil and many other languages exist that implement this pattern.

In prototype system, there are no classes. Infact, JS has no classes either in true sense and the ES6 classes you use is just a syntactic sugar over the prototypes. What that means is behind the scene JS writes a prototype based code that makes your class based code work.

Class-based languages are based on a deep-rooted duality of Classes & Object Instances. For instance, if we create an object of the class Vehicle, such as Red Car, and ask it to deliver a super heavy material, it will not be feasible because Red Car is not equipped for that and it is something that's wired in Vehicle class. This highlights the importance of subclassing, which enables creating specialized classes, such as Sports Car and Truck, with their own unique capabilities.

However, predicting the future qualities of objects and classes is challenging, and systems can become rigid when the initial design does not anticipate future changes. And this was one of the motivation to create prototype feature, as such use cases occur in real world development all the time.

Behaviour Delegation

In JavaScript, behavior delegation refers to a programming pattern where an object delegates certain behaviors or methods to another object. This pattern is based on the concept of prototypal inheritance, where objects can inherit properties and methods from other objects.

Instead of using class-based inheritance, behavior delegation allows objects to directly reference and delegate to other objects, known as prototypes. When a method is invoked on an object, JavaScript looks for that method in the object’s prototype chain, searching for the first object that implements the method.

This pattern promotes code reuse and flexibility, as objects can dynamically delegate behavior to different prototypes at runtime. It is commonly used in JavaScript to achieve composition and create flexible object relationships. The Object.create() method and the [[Prototype]] mechanism are key features supporting behavior delegation in JavaScript.