How to use mixins properly in Javascript

A mixin is just a different conceptual idea, of how to organize code and inheritance. You can of course combine it with using classical or prototypal inheritance, but it also works stand-alone, so to speak.

For instance, instead of creating “delegated” object properties/lookups (like prototypal inheritance), we would truly “form” new stand-alone objects, from multiple other objects. This is also called “multiple inheritance” sometimes and that cannot get achieved easily with Javascripts prototypal inheritance alone.

As an example:

var pianist = {
   play: function() {}
};

var programmner: {
   code: function() {}
};

And now we could create another Object, like

var Jim = Object.create( null ); // create a fully self-defining object

extend( Jim, pianist );
extend( Jim, programmer );

and this pseudo extend method could look like (ES5):

function extend( target, source ) {
    Object.getOwnPropertyNames( source ).forEach(function( key ) {
        Object.defineProperty( target, key, Object.getOwnPropertyDescriptor(source, key)) });

    return target
}

I actually didn’t answer your questions properly, but I felt like there is no real answer to your question. It is as real as you are going to use it, there is no “application specific” use case really.

Leave a Comment