|
| 1 | +# 6. Code reuse patterns |
| 2 | + |
| 3 | +Prefer composition over inheritance. |
| 4 | + |
| 5 | +## classical inheritance |
| 6 | + |
| 7 | +* play on the word 'class', nothing to do with the word classical |
| 8 | +* JavaScript has no classes but constructor functions make same people think that |
| 9 | +* use the term constructor function |
| 10 | + |
| 11 | +```js |
| 12 | +function Parent(){ } |
| 13 | +function Child(){ } |
| 14 | +//inheritance magic happens here |
| 15 | +inherit(Child, Parent); |
| 16 | +``` |
| 17 | + |
| 18 | +* inherit is not part of the language have to implement it yourself |
| 19 | + |
| 20 | +## classical inheritance with default pattern |
| 21 | + |
| 22 | +```js |
| 23 | +function inherit(Child, Parent){ |
| 24 | + child.prototype = new Parent(); |
| 25 | +} |
| 26 | +``` |
| 27 | +* prototype points at new parent object |
| 28 | +* children gets parent functionality via prototype |
| 29 | +* drawback: children gets both own and prototype properties from parent |
| 30 | +* drawback: can't really pass parameters, or end up with a lot of objects |
| 31 | + |
| 32 | + |
| 33 | +## the prototype chain |
| 34 | + |
| 35 | +* can think of objects as blocks of memory |
| 36 | +* all objects from the same constructor point at same prototype object |
| 37 | +* can think of it as if they were pointing at it via a ```__proto__``` property |
| 38 | +* ```__proto__``` is actually available in some JavaScript environments |
| 39 | +* properties are looked up by walking through this prototype chain: |
| 40 | +* if an object doesn't have a property it's ```__proto__``` is consulted |
| 41 | + |
| 42 | +## classical inheritance with rent-a-constructor pattern |
| 43 | + |
| 44 | +```js |
| 45 | +function Child(a, b, c, d){ |
| 46 | + Parent.apply(this, arguments); |
| 47 | +} |
| 48 | +``` |
| 49 | +* solves the problem of passing arguments |
| 50 | +* borrows parent constructor |
| 51 | +* passing the child object to be bound to this |
| 52 | +* and passing any arguments |
| 53 | +* children does not inherit prototype properties |
| 54 | +* but gets true copies of own properties (not links) |
| 55 | +* inheritance is just a one of action |
| 56 | +* only copying own properties from parent |
| 57 | +* no proto links are kept, can't access parent prototype properties |
| 58 | +* multiple inheritance can be achieved by applying more than one constructors |
| 59 | +* in case of multiple inheritance and duplicate properties - last one wins |
0 commit comments