在Javascript库中,mixin()和extend()有什么区别? [英] What's the difference between mixin() and extend() in Javascript libraries

查看:306
本文介绍了在Javascript库中,mixin()和extend()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看各种图书馆,并看到extend()弹出很多,但我也看到mixin()显示。 YUI有混合和扩展。



这两个概念有什么区别?我什么时候决定一个混合和扩展一个对象?



谢谢,
Matt

解决方案

Mixins不能与instanceof一起工作,而是扩展。 Mixins允许多个继承,但是通过伪造它,而不是正确链接原型。



我将显示一个Ext-JS示例,但该概念适用于提供的任何类库mixins,它们都只是将属性复制到对象而不是链接原型。

  Ext.define('Ext.Window' {
extends:'Ext.Panel',
要求:'Ext.Tool',
mixins:{
draggable:'Ext.util.Draggable'
}
});

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

Mixins是一种在不使用继承的情况下向对象添加一些功能的好方法。如果您必须继承某些功能才能获得某些功能,那么您不能使用两个中的功能。 许多人认为它是邪恶的



Ext-JS在将可标签功能添加到 FieldSet 和其他没有输入的字段。没有办法可以从 Field 中的 Labelable 行为中受益,因为它们不能扩展 Field ,因为它也有所有的输入行为。


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

解决方案

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.

这篇关于在Javascript库中,mixin()和extend()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆