Creating and using mixins

The term mixin is usually used to specify a collection of functions available to be shared among objects or classes. It can be somehow considered similar to abstract classes in classical OOP languages. Usually, the mixin functions are not directly used, but they are borrowed to others objects or classes in order to extend them without creating a strict relationship as it could be with inheritance. Let's introduce mixins in JavaScript with a simple example.

Mixing prototypes

Consider our Person() constructor function in its minimal implementation:

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

Then consider a simple object literal implementing a getFullName() method that returns the full name ...

Get Mastering JavaScript Object-Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.