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:
-
Higher-order functions and function composition — creating small functions that can be combined to achieve the desired behavior.
-
Mixins — objects or functions that add functionality to other objects through property copying.
-
Decorators — functions that wrap other functions, extending their behavior.
-
Modules — isolating reusable code into separate files or namespaces.
-
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.