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

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

问题描述

我正在浏览各种库,看到很多扩展()弹出,但我也看到 mixin()出现.YUI 既有 mixin 也有扩展.

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.

这两个概念有什么区别?我什么时候会在 mixin 和扩展对象之间做出决定?

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

谢谢,马特

推荐答案

Mixins 不适用于 instanceof 但 extends 可以.Mixin 允许多重继承,但通过伪造它,而不是通过正确链接原型.

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

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

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 是一种无需借助继承即可向对象添加某些功能的好方法.如果你必须继承一些东西来获得一些功能,那么你就不能使用来自两个的功能.许多人认为这是邪恶的.

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 在他们想要将 Labelable 功能添加到 FieldSet 和其他非输入字段时遇到了这个问题.它无法从 Field 内的 Labelable 行为中受益,因为它们无法扩展 Field 因为它具有所有输入行为它也是.

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天全站免登陆