File tree 1 file changed +49
-0
lines changed
chapters/classes_and_objects
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ layout : recipe
3
+ title : Mixins for classes
4
+ chapter : Classes and Objects
5
+ ---
6
+ ## Problem
7
+
8
+ You have a few utility methods that you want to include in a number of different classes.
9
+
10
+ ## Solution
11
+
12
+ Use a mixOf factory function that generates a mixed superclass for you.
13
+
14
+ {% highlight coffeescript %}
15
+ mixOf = (base, mixins...) ->
16
+ class Mixed extends base
17
+ for mixin in mixins by -1 #earlier mixins override later ones
18
+ for name, method of mixin::
19
+ Mixed::[ name] = method
20
+ Mixed
21
+
22
+ ...
23
+
24
+ class DeepThought
25
+ answer: ->
26
+ 42
27
+
28
+ class PhilosopherMixin
29
+ pontificate: ->
30
+ console.log "hmm..."
31
+ @wise = yes
32
+
33
+ class DeeperThought extends mixOf DeepThought, PhilosopherMixin
34
+ answer: ->
35
+ @pontificate ()
36
+ super()
37
+
38
+ earth = new DeeperThought
39
+ earth.answer()
40
+ # hmm...
41
+ # => 42
42
+ {% endhighlight %}
43
+
44
+ ## Discussion
45
+
46
+ This is intended for lightweight mixins. Thus you inherit methods of the
47
+ base and its ancestors, and those of the mixins, but not those of the ancestors of
48
+ the mixins. Also, after declaring a mixed class, further changes in the mixins are not
49
+ reflected.
You can’t perform that action at this time.
0 commit comments