问题
in the classfull-Style (c++) or in the traditional Design Patterns (GofPatterns) it is really clear, what is the difference between composition and inheritance and how it is implemented and when to use what (advantages/disadvantages).
But how do you distingish between Composition or the "normal" Inheritance in JS? or it is used as the same term?
Is a prototype inheritance for example defined as a composition or inheritance?
What are you guys thinking?
回答1:
Is a prototype inheritance for example defined as a composition or inheritance?
What are you guys thinking?
It is not about what I’m thinking but what the language core provides …
in the classfull-Style (c++) or in the traditional Design Patterns (GofPatterns) it is really clear, what is the difference between composition and inheritance and how it is implemented and when to use what (advantages/disadvantages).
But how do you distingish between Composition or the "normal" Inheritance in JS? or it is used as the same term?
… and of course one shouldn't bend concepts to much. Thus for JavaScript too, composition and inheritance count as much as for any other PL that supports these paradigms. JavaScript features Delegation, which already enables two variants of Code-reuse. Firstly, Inheritance, which in JavaScript is covered by a delegation automatism that is bound to the [prototype]
property of constructor functions. Secondly, Object Composition, which is based on explicitly delegating a function via one of it's call methods ([call]
or [apply]
).
Summing it up:
- Prototypal Delegation (Automatism) == Inheritance
- Explicit Delegation of Function Objects == Role based composition concepts like Mixins and Traits / Talents
- stepwise copying properties from one objects to another == another way of achieving kind of mixin composition
I already did provide examples in two other responses that are …
- stackoverflow.com :: Traits in javascript
- stackoverflow.com :: How to use mixins properly in Javascript
回答2:
As I first learned Java, I was tempted to try to do the same thing with Javascript. But it was a wrong idea. Javascript allows to do oriented-object programming. The way OOP is done with Javascript is different from C++ or Java: it is the way you use it that allows OOP, not the language itself.
I recommend you these links to properly learn about how Javascript can be used:
http://javascriptissexy.com/how-to-learn-javascript-properly/
http://javascriptissexy.com/learn-intermediate-and-advanced-javascript/
来源:https://stackoverflow.com/questions/24288926/javascript-distinguish-between-composition-vs-inheritance