Member-only story
Amongst the many approaches to achieving inheritance in JavaScript, factory functions stand out due to their simplicity, flexibility, and ease of use. They allow you to create instances of objects while avoiding cumbersome class definitions and awkward boilerplates. This post explores factory functions for inheritance and explains how they can streamline your codebase.
A quick refresher on factory functions: they essentially serve as constructors returning newly created objects after applying certain logic. You don’t need the new
operator to invoke them, unlike regular constructors.
So, how do we implement inheritance with factory functions? Below is an example highlighting the process:
// Define Parent Factory Function
const vehicleFactory = ({ color, brand }) => ({
honk() {
console.log('Beep Beep!');
},
getColor() {
return color;
},
setColor(value) {
color = value;
},
getBrand() {
return brand;
},
});
// Implement Child Factory Function
const carFactory = (parentProps) => {
const v = vehicleFactory(parentProps);
const accelerate = () => {
console.log('Vroom Vroom!');
};
return { ...v, accelerate, wheelsCount: 4 };
};
//…