问题
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.
The most common way to do this is with the new
keyword, but you can also implement object.create()
.
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.
What are the advantages and drawbacks of each pattern in JS?
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.
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.
回答1:
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.
来源:https://stackoverflow.com/questions/31629027/delegation-vs-concatenation-in-javascript