Java中的委派VS串联 [英] Delegation VS Concatenation in Javascript

查看:45
本文介绍了Java中的委派VS串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript缺少类构造,但是您仍然可以通过许多不同的方法来实现继承.

Javascript lacks a class construct, however you can still achieve inheritance many different ways.

您可以通过利用原型来创建构造函数并通过委托实现继承来模仿类.

You can mimic classes by utilizing prototypes to create constructor functions and thus implementing inheritance via delegation.

最常见的方法是使用 new 关键字,但是您也可以实现 object.create().

The most common way to do this is with the new keyword, but you can also implement object.create().

或者,您可以采用串联方法并将想要对象继承的行为复制到对象本身中,而不是将其 [[prototype]] 指向另一个对象.

Alternatively, you can take a concatenative approach and copy behavior that you want your object to inherit directly into the object itself, rather than by pointing its [[prototype]] to another object.

JS中每种模式的优缺点是什么?

What are the advantages and drawbacks of each pattern in JS?

似乎很多专家都在倡导级联方法,例如Doug Crockford.但是,目前,委派模式显然更受欢迎.

It seems many experts are advocating the concatenative approach, like Doug Crockford for example. The delegation pattern is clearly more popular at the moment, however.

我知道,一般而言,级联方法将更加灵活,但是会消耗更多的内存,因为您的复制方法遍布整个地方,而不仅仅是引用一个公共集合.

I know that, in general, the concatenative approach is going to be more flexible, but will consume more memory because your copying methods all over the place rather than just referencing a common set.

但是,我也知道V8引擎可以优化这些内容.

However, I also know that the V8 engine has ways of optimizing this stuff.

除了性能之外,您还可以通过串联实现通过串联实现的任何东西吗?例如,在委托中,我可以在超类中有一个实现一些基本功能的方法,而在我的子类方法中,我可以调用超类的方法,然后在返回最终结果之前进行一些特定于子类的计算.我想不出一种方法,而不仅仅是使用不同的方法名称就可以使用串联方法.

Besides performance, is there anything that you can achieve via delegation that you can achieve via concatenation? For example, in delegation, I can have a method in a super class that implements some basic functionality and in my subclass methods I can call the super's method and then do some subclass-specific computations before returning the final result. I can't think of a way to do this with the concatenative approach without just using a different method name.

推荐答案

主要区别在于对象的大小和灵活性.继承属性而不是复制它们会导致对象变小,尤其是在您的方法API相对较大的情况下.而且,从仍然可以操纵的单个对象继承属性的动态性要高得多(请参阅某些JavaScript库是否使用了原型系统的动态方面??).优化可能要比从静态对象继承要复杂得多,但是比不共享对象之间的共享要快.

The main differences are object size and flexibility. Inheriting properties instead of copying them will lead to smaller objects, especially if your method API is relatively large. Also, inheriting properties from a single object that can still be manipulated is much more dynamic (see Does some JavaScript library use dynamic aspects of the prototype system?). It might be more complicated to optimize than inheriting from static objects, but it is still faster than not sharing between objects.

这篇关于Java中的委派VS串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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