The mixin pattern

Mixins help in significantly reducing functional repetition in our code and help in function reuse. We can move this shared functionality to a mixin and reduce duplication of shared behavior. You can then focus on building the actual functionality and not keep repeating the shared behavior. Let's consider the following example. We want to create a custom logger that can be used by any object instance. The logger will become a functionality shared across objects that want to use/extend the mixin:

var _ = require('underscore'); //Shared functionality encapsulated into a CustomLogger var logger = (function () { var CustomLogger = { log: function (message) { console.log(message); } }; return CustomLogger; }()); //An object that will ...

Get Mastering JavaScript 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.