Sobes.tech
Junior — Middle

What approaches exist in JavaScript for implementing code reuse without using prototypal inheritance?

sobes.tech AI

Answer from AI

In JavaScript, the following approaches are often used for code reuse without prototypal inheritance:

  1. Higher-order functions and function composition — creating small functions that can be combined to achieve the desired behavior.

  2. Mixins — objects or functions that add functionality to other objects through property copying.

  3. Decorators — functions that wrap other functions, extending their behavior.

  4. Modules — isolating reusable code into separate files or namespaces.

  5. Classes using composition instead of inheritance — including objects as properties instead of inheritance.

Example of a mixin:

const canEat = {
  eat() {
    console.log('Eating');
  }
};

const canWalk = {
  walk() {
    console.log('Walking');
  }
};

function createPerson(name) {
  let person = { name };
  return Object.assign(person, canEat, canWalk);
}

const person = createPerson('John');
person.eat(); // Eating
person.walk(); // Walking

Thus, code reuse is achieved through composition and combining functionalities, rather than through prototypal inheritance.

What approaches exist in JavaScript for implementing… - sobes.tech