What's the difference between mixin() and extend() in Javascript libraries

Matt picture Matt · Sep 21, 2011 · Viewed 10.7k times · Source

I'm looking through various libraries, and seeing extend() pop up a lot, but I'm also seeing mixin() show up. YUI has both mixins and extensions.

What's the difference between these two concepts? When would I decide between a mixin and extending an object?

Thanks, Matt

Answer

Juan Mendes picture Juan Mendes · Sep 21, 2011

Mixins don't work with instanceof but extends do. Mixins allow multiple inheritance but by faking it, not by properly chaining the prototypes.

I'll show an Ext-JS example but the concept applies to any class library that provides mixins, they all just copy properties to the object instead of chaining the prototype.

Ext.define('Ext.Window', {
    extend: 'Ext.Panel',
    requires: 'Ext.Tool',
    mixins: {
        draggable: 'Ext.util.Draggable'
    }
});

Ext.Window instanceof Ext.Panel //true
Ext.Window instanceof Ext.util.Draggable // false

Mixins are a great way to add some functionality to an object without resorting to inheritance. If you have to inherit something to get some functionality, then you can't use functionality from two classes. Many people believe it's evil.

Ext-JS experienced that problem when they wanted to add Labelable functionality to FieldSet and others that were not input like fields. There was no way that it could benefit from the Labelable behavior inside Field since they couldn't extend Field since it had all the input behavior in it too.