JavaScript中的多重继承/原型 [英] Multiple inheritance/prototypes in JavaScript

查看:154
本文介绍了JavaScript中的多重继承/原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经到了需要在JavaScript中进行某种基本的多重继承的地步。 (我不是来讨论这是不是一个好主意,所以请将这些意见保留给自己。)



我只是想知道是否有人尝试过这有没有(或没有)成功,以及他们如何去做。



要把它煮沸,我真正需要的是能够拥有一个能够从多个原型继承属性(即每个原型可以有自己的链接),但是在给定的优先顺序中(它将搜索链以便进行第一个定义)。 / p>

为了证明这在理论上是如何可行的,可以通过将辅助链附加到主链的末端来实现,但这会影响以前任何一个的所有实例。原型,这不是我想要的。



想法?



编辑
欣赏响应的人,但是虽然共识似乎是静态地复制了来自bot的属性h树,在大多数情况下都可以工作(并且可能就是我最终要做的事情),我最感兴趣的是一个动态解决方案,它可以改变单独的原型链,并且仍然可以通过实例。

解决方案

Mixins 可用于javascript,以实现您目前可能希望通过多重继承解决的相同目标。


I've come to a point where I need to have some sort of rudimentary multiple inheritance happening in JavaScript. (I'm not here to discuss whether this is a good idea or not, so please kindly keep those comments to yourself.)

I just want to know if anyone's attempted this with any (or not) success, and how they went about it.

To boil it down, what I really need is to be able to have an object capable of inheriting a property from more than one prototype chain (i.e. each prototype could have its own proper chain), but in a given order of precedence (it will search the chains in order for the first definition).

To demonstrate how this is theoretically possible, it could be achieved by attaching the secondary chain onto the end of the primary chain, but this would affect all instances of any of those previous prototypes and that's not what I want.

Thoughts?

Edit Appreciate the responses folks, but while the consensus seems to be statically copying over the properties from both trees, which would work in most cases (and will probably be what I end up doing), I was most interested in a dynamic solution that would allow the separate prototype chains to be altered, and still have those changes "picked up" by the instance.

解决方案

Mixins can be used in javascript to achieve the same goal you probably want to solve via multiple inheritance at the moment.

这篇关于JavaScript中的多重继承/原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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