Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...