-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path06_object.html
More file actions
924 lines (905 loc) · 85.8 KB
/
06_object.html
File metadata and controls
924 lines (905 loc) · 85.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
<!doctype html>
<head>
<meta charset="utf-8">
<title>The Secret Life of Objects :: Eloquent JavaScript</title>
<link rel=stylesheet href="js/node_modules/codemirror/lib/codemirror.css">
<script src="js/acorn_codemirror.js"></script>
<link rel=stylesheet href="css/ejs.css">
<script src="js/sandbox.js"></script>
<script src="js/ejs.js"></script>
<script>var chapNum = 6;var sandboxLoadFiles = ["code/mountains.js", "code/chapter/06_object.js"];</script>
</head>
<article>
<nav>
<a href="05_higher_order.html" title="previous chapter">◀</a>
<a href="index.html" title="cover">◆</a>
<a href="07_elife.html" title="next chapter">▶</a>
</nav>
<h1><div class=chap_num>Chapter 6</div>The Secret Life of Objects</h1>
<blockquote>
<p><a class=p_ident id="p_C9NMk2tmA4" href="#p_C9NMk2tmA4"></a>The problem with object-oriented languages
is they’ve got all this implicit environment that they carry around
with them. You wanted a banana but what you got was a gorilla holding
the banana and the entire jungle.</p>
<footer>Joe Armstrong, <cite>interviewed in Coders at Work</cite></footer>
</blockquote>
<p><a class=p_ident id="p_fPdVAHtS9s" href="#p_fPdVAHtS9s"></a>When a programmer
says “object”, this is a loaded term. In my profession, objects are a
way of life, the subject of holy wars, and a beloved buzzword that
still hasn’t quite lost its power.</p>
<p><a class=p_ident id="p_1l/AXS0w/+" href="#p_1l/AXS0w/+"></a>To an outsider, this is probably a little confusing. Let’s start with
a brief history of objects as a programming construct.</p>
<h2><a class=h_ident id="h_kMzWSXQAtV" href="#h_kMzWSXQAtV"></a>History</h2>
<p><a class=p_ident id="p_7Qth+HqmZl" href="#p_7Qth+HqmZl"></a>This story, like most programming stories, starts with the
problem of complexity. One philosophy is that complexity can be
made manageable by separating it into small compartments that are
isolated from each other. These compartments have ended up with the
name <em>objects</em>.</p>
<p id="interface"><a class=p_ident id="p_UuUhBp47+J" href="#p_UuUhBp47+J"></a>An
object is a hard shell that hides the gooey complexity inside it
and instead offers us a few knobs and connectors (such as methods)
that present an <em>interface</em> through which the object is to be used.
The idea is that the interface is relatively simple and all the
complex things going on <em>inside</em> the object can be ignored when
working with it.</p>
<div class="image">
<img src="img/object.jpg" alt="A simple interface can hide a lot of complexity.">
</div>
<p><a class=p_ident id="p_KUiP7xA3eo" href="#p_KUiP7xA3eo"></a>As an example, you can imagine an object that provides an interface to
an area on your screen. It provides a way to draw shapes or text onto
this area but hides all the details of how these shapes are converted
to the actual pixels that make up the screen. You’d have a set of
methods—for example, <code>drawCircle</code>—and those are the only things you
need to know in order to use such an object.</p>
<p><a class=p_ident id="p_2cwmac7A3z" href="#p_2cwmac7A3z"></a>These ideas were initially worked out
in the 1970s and 1980s and, in the 1990s, were carried up by a huge wave
of hype—the object-oriented programming revolution. Suddenly,
there was a large tribe of people declaring that objects were the
<em>right</em> way to program—and that anything that did not involve objects
was outdated nonsense.</p>
<p><a class=p_ident id="p_g9yaxQcUB0" href="#p_g9yaxQcUB0"></a>That kind of zealotry always produces a lot of impractical silliness,
and there has been a sort of counter-revolution since then. In some
circles, objects have a rather bad reputation nowadays.</p>
<p><a class=p_ident id="p_yDJcWLiV1q" href="#p_yDJcWLiV1q"></a>I prefer to look at the issue from a practical, rather than
ideological, angle. There are several useful concepts, most
importantly that of <em>encapsulation</em> (distinguishing between
internal complexity and external interface), that the object-oriented
culture has popularized. These are worth studying.</p>
<p><a class=p_ident id="p_uZjg5Fd1Wj" href="#p_uZjg5Fd1Wj"></a>This chapter describes JavaScript’s rather eccentric take on objects
and the way they relate to some classical object-oriented techniques.</p>
<h2 id="obj_methods"><a class=h_ident id="h_fkrGgDyRWc" href="#h_fkrGgDyRWc"></a>Methods</h2>
<p><a class=p_ident id="p_cbCII9cU5W" href="#p_cbCII9cU5W"></a>Methods are simply
properties that hold function values. This is a simple method:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_l1xlJAtYi3" href="#c_l1xlJAtYi3"></a><span class="cm-keyword">var</span> <span class="cm-variable">rabbit</span> <span class="cm-operator">=</span> {};
<span class="cm-variable">rabbit</span>.<span class="cm-property">speak</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">line</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"The rabbit says '"</span> <span class="cm-operator">+</span> <span class="cm-variable-2">line</span> <span class="cm-operator">+</span> <span class="cm-string">"'"</span>);
};
<span class="cm-variable">rabbit</span>.<span class="cm-property">speak</span>(<span class="cm-string">"I'm alive."</span>);
<span class="cm-comment">// → The rabbit says 'I'm alive.'</span></pre>
<p><a class=p_ident id="p_N+6e0UGvFo" href="#p_N+6e0UGvFo"></a>Usually a method needs to do something with
the object it was called on. When a function is called as a
method—looked up as a property and immediately called, as in
<code>object.method()</code>—the special variable <code>this</code> in its body will point
to the object that it was called on.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_nD7BzYTooL" href="#c_nD7BzYTooL"></a><span class="cm-keyword">function</span> <span class="cm-variable">speak</span>(<span class="cm-def">line</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"The "</span> <span class="cm-operator">+</span> <span class="cm-keyword">this</span>.<span class="cm-property">type</span> <span class="cm-operator">+</span> <span class="cm-string">" rabbit says '"</span> <span class="cm-operator">+</span>
<span class="cm-variable-2">line</span> <span class="cm-operator">+</span> <span class="cm-string">"'"</span>);
}
<span class="cm-keyword">var</span> <span class="cm-variable">whiteRabbit</span> <span class="cm-operator">=</span> {<span class="cm-property">type</span>: <span class="cm-string">"white"</span>, <span class="cm-property">speak</span>: <span class="cm-variable">speak</span>};
<span class="cm-keyword">var</span> <span class="cm-variable">fatRabbit</span> <span class="cm-operator">=</span> {<span class="cm-property">type</span>: <span class="cm-string">"fat"</span>, <span class="cm-property">speak</span>: <span class="cm-variable">speak</span>};
<span class="cm-variable">whiteRabbit</span>.<span class="cm-property">speak</span>(<span class="cm-string">"Oh my ears and whiskers, "</span> <span class="cm-operator">+</span>
<span class="cm-string">"how late it's getting!"</span>);
<span class="cm-comment">// → The white rabbit says 'Oh my ears and whiskers, how</span>
<span class="cm-comment">// late it's getting!'</span>
<span class="cm-variable">fatRabbit</span>.<span class="cm-property">speak</span>(<span class="cm-string">"I could sure use a carrot right now."</span>);
<span class="cm-comment">// → The fat rabbit says 'I could sure use a carrot</span>
<span class="cm-comment">// right now.'</span></pre>
<p><a class=p_ident id="p_FbPIv/+6x+" href="#p_FbPIv/+6x+"></a>The
code uses the <code>this</code> keyword to output the type of rabbit that is
speaking. Recall that the <code>apply</code> and <code>bind</code> methods both take a first
argument that can be used to simulate method calls. This first
argument is in fact used to give a value to <code>this</code>.</p>
<p id="call_method"><a class=p_ident id="p_jHNP07w/lm" href="#p_jHNP07w/lm"></a>There is a method similar to <code>apply</code>, called <code>call</code>.
It also calls the function it is a method of but takes its arguments
normally, rather than as an array. Like <code>apply</code> and <code>bind</code>, <code>call</code> can
be passed a specific <code>this</code> value.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_hpZYGIH9dn" href="#c_hpZYGIH9dn"></a><span class="cm-variable">speak</span>.<span class="cm-property">apply</span>(<span class="cm-variable">fatRabbit</span>, [<span class="cm-string">"Burp!"</span>]);
<span class="cm-comment">// → The fat rabbit says 'Burp!'</span>
<span class="cm-variable">speak</span>.<span class="cm-property">call</span>({<span class="cm-property">type</span>: <span class="cm-string">"old"</span>}, <span class="cm-string">"Oh my."</span>);
<span class="cm-comment">// → The old rabbit says 'Oh my.'</span></pre>
<h2 id="prototypes"><a class=h_ident id="h_SumMlRB7yn" href="#h_SumMlRB7yn"></a>Prototypes</h2>
<p><a class=p_ident id="p_hi1TWnD/2p" href="#p_hi1TWnD/2p"></a>Watch closely.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_i8erz5n1Nn" href="#c_i8erz5n1Nn"></a><span class="cm-keyword">var</span> <span class="cm-variable">empty</span> <span class="cm-operator">=</span> {};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">empty</span>.<span class="cm-property">toString</span>);
<span class="cm-comment">// → function toString(){…}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">empty</span>.<span class="cm-property">toString</span>());
<span class="cm-comment">// → [object Object]</span></pre>
<p><a class=p_ident id="p_aX24Mkkmn9" href="#p_aX24Mkkmn9"></a>I just pulled a property out of an empty object. Magic!</p>
<p><a class=p_ident id="p_ymaGpRwPF5" href="#p_ymaGpRwPF5"></a>Well, not really. I have simply been
withholding information about the way JavaScript objects work. In
addition to their set of properties, almost all objects also have a
<em>prototype</em>. A prototype is another object that is used as a
fallback source of properties. When an object gets a request for a
property that it does not have, its prototype will be searched for the
property, then the prototype’s prototype, and so on.</p>
<p><a class=p_ident id="p_7FLJjsfmk4" href="#p_7FLJjsfmk4"></a>So who is the prototype of that empty
object? It is the great ancestral prototype, the entity behind almost
all objects, <code>Object.prototype</code>.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_nuBDtl0kQy" href="#c_nuBDtl0kQy"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">getPrototypeOf</span>({}) <span class="cm-operator">==</span>
<span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">getPrototypeOf</span>(<span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>));
<span class="cm-comment">// → null</span></pre>
<p><a class=p_ident id="p_vHbNlN1h5h" href="#p_vHbNlN1h5h"></a>As you might expect, the
<code>Object.getPrototypeOf</code> function returns the prototype of an object.</p>
<p><a class=p_ident id="p_4S0XbM8aBm" href="#p_4S0XbM8aBm"></a>The prototype relations of JavaScript objects
form a tree-shaped structure, and at the root of this structure
sits <code>Object.prototype</code>. It provides a few methods that show up in
all objects, such as <code>toString</code>, which converts an object to a string
representation.</p>
<p><a class=p_ident id="p_LPg9dSSFAi" href="#p_LPg9dSSFAi"></a>Many objects don’t directly have
<code>Object.prototype</code> as their prototype, but instead have another
object, which provides its own default properties. Functions derive
from <code>Function.prototype</code>, and arrays derive from <code>Array.prototype</code>.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_sV0BBBJ/w/" href="#c_sV0BBBJ/w/"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">getPrototypeOf</span>(<span class="cm-variable">isNaN</span>) <span class="cm-operator">==</span>
<span class="cm-variable">Function</span>.<span class="cm-property">prototype</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">getPrototypeOf</span>([]) <span class="cm-operator">==</span>
<span class="cm-variable">Array</span>.<span class="cm-property">prototype</span>);
<span class="cm-comment">// → true</span></pre>
<p><a class=p_ident id="p_QVomcVCyPH" href="#p_QVomcVCyPH"></a>Such a prototype object will itself have a
prototype, often <code>Object.prototype</code>, so that it still indirectly
provides methods like <code>toString</code>.</p>
<p><a class=p_ident id="p_TzOd94K1HD" href="#p_TzOd94K1HD"></a>The <code>Object.getPrototypeOf</code> function obviously returns the
prototype of an object. You can use <code>Object.create</code> to create an
object with a specific prototype.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_9H47vWZ096" href="#c_9H47vWZ096"></a><span class="cm-keyword">var</span> <span class="cm-variable">protoRabbit</span> <span class="cm-operator">=</span> {
<span class="cm-property">speak</span>: <span class="cm-keyword">function</span>(<span class="cm-def">line</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"The "</span> <span class="cm-operator">+</span> <span class="cm-keyword">this</span>.<span class="cm-property">type</span> <span class="cm-operator">+</span> <span class="cm-string">" rabbit says '"</span> <span class="cm-operator">+</span>
<span class="cm-variable-2">line</span> <span class="cm-operator">+</span> <span class="cm-string">"'"</span>);
}
};
<span class="cm-keyword">var</span> <span class="cm-variable">killerRabbit</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-variable">protoRabbit</span>);
<span class="cm-variable">killerRabbit</span>.<span class="cm-property">type</span> <span class="cm-operator">=</span> <span class="cm-string">"killer"</span>;
<span class="cm-variable">killerRabbit</span>.<span class="cm-property">speak</span>(<span class="cm-string">"SKREEEE!"</span>);
<span class="cm-comment">// → The killer rabbit says 'SKREEEE!'</span></pre>
<p><a class=p_ident id="p_y8kzFoQw1W" href="#p_y8kzFoQw1W"></a>The “proto” rabbit acts as a container for the
properties that are shared by all rabbits. An individual rabbit
object, like the killer rabbit, contains properties that apply only to
itself—in this case its type—and derives shared properties from its
prototype.</p>
<h2 id="constructors"><a class=h_ident id="h_YKXJZqcaJA" href="#h_YKXJZqcaJA"></a>Constructors</h2>
<p><a class=p_ident id="p_y83XvnG8ez" href="#p_y83XvnG8ez"></a>A more convenient way to create objects that derive
from some shared prototype is to use a <em>constructor</em>. In
JavaScript, calling a function with the <code>new</code> keyword in front of it
causes it to be treated as a constructor. The constructor will have
its <code>this</code> variable bound to a fresh object, and unless it explicitly
returns another object value, this new object will be returned from
the call.</p>
<p><a class=p_ident id="p_uPw4dUu94k" href="#p_uPw4dUu94k"></a>An object created with <code>new</code> is said to be an <em>instance</em> of its
constructor.</p>
<p><a class=p_ident id="p_v2jJnPrF/1" href="#p_v2jJnPrF/1"></a>Here is a simple constructor
for rabbits. It is a convention to capitalize the names of
constructors so that they are easily distinguished from other
functions.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_Th/OJfySgB" href="#c_Th/OJfySgB"></a><span class="cm-keyword">function</span> <span class="cm-variable">Rabbit</span>(<span class="cm-def">type</span>) {
<span class="cm-keyword">this</span>.<span class="cm-property">type</span> <span class="cm-operator">=</span> <span class="cm-variable-2">type</span>;
}
<span class="cm-keyword">var</span> <span class="cm-variable">killerRabbit</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Rabbit</span>(<span class="cm-string">"killer"</span>);
<span class="cm-keyword">var</span> <span class="cm-variable">blackRabbit</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">Rabbit</span>(<span class="cm-string">"black"</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">blackRabbit</span>.<span class="cm-property">type</span>);
<span class="cm-comment">// → black</span></pre>
<p><a class=p_ident id="p_ZZ4u3YPk72" href="#p_ZZ4u3YPk72"></a>Constructors (in fact, all
functions) automatically get a property named <code>prototype</code>, which by
default holds a plain, empty object that derives from
<code>Object.prototype</code>. Every instance created with this constructor will
have this object as its prototype. So to add a <code>speak</code> method to
rabbits created with the <code>Rabbit</code> constructor, we can simply do this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_NxM9pC8Uab" href="#c_NxM9pC8Uab"></a><span class="cm-variable">Rabbit</span>.<span class="cm-property">prototype</span>.<span class="cm-property">speak</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">line</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"The "</span> <span class="cm-operator">+</span> <span class="cm-keyword">this</span>.<span class="cm-property">type</span> <span class="cm-operator">+</span> <span class="cm-string">" rabbit says '"</span> <span class="cm-operator">+</span>
<span class="cm-variable-2">line</span> <span class="cm-operator">+</span> <span class="cm-string">"'"</span>);
};
<span class="cm-variable">blackRabbit</span>.<span class="cm-property">speak</span>(<span class="cm-string">"Doom..."</span>);
<span class="cm-comment">// → The black rabbit says 'Doom...'</span></pre>
<p><a class=p_ident id="p_4sWuvx6wkg" href="#p_4sWuvx6wkg"></a>It is important
to note the distinction between the way a prototype is associated with
a constructor (through its <code>prototype</code> property) and the way objects
<em>have</em> a prototype (which can be retrieved with
<code>Object.getPrototypeOf</code>). The actual prototype of a constructor is
<code>Function.prototype</code> since constructors are functions. Its
<code>prototype</code> <em>property</em> will be the prototype of instances created
through it but is not its <em>own</em> prototype.</p>
<h2><a class=h_ident id="h_oUlUep3Os8" href="#h_oUlUep3Os8"></a>Overriding derived properties</h2>
<p><a class=p_ident id="p_TULrs9Y+I2" href="#p_TULrs9Y+I2"></a>When you add a property to an
object, whether it is present in the prototype or not, the property is
added to the object <em>itself</em>, which will henceforth have it as its own
property. If there <em>is</em> a property by the same name in the prototype,
this property will no longer affect the object. The prototype itself
is not changed.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_QARcjiyYI7" href="#c_QARcjiyYI7"></a><span class="cm-variable">Rabbit</span>.<span class="cm-property">prototype</span>.<span class="cm-property">teeth</span> <span class="cm-operator">=</span> <span class="cm-string">"small"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">killerRabbit</span>.<span class="cm-property">teeth</span>);
<span class="cm-comment">// → small</span>
<span class="cm-variable">killerRabbit</span>.<span class="cm-property">teeth</span> <span class="cm-operator">=</span> <span class="cm-string">"long, sharp, and bloody"</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">killerRabbit</span>.<span class="cm-property">teeth</span>);
<span class="cm-comment">// → long, sharp, and bloody</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">blackRabbit</span>.<span class="cm-property">teeth</span>);
<span class="cm-comment">// → small</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Rabbit</span>.<span class="cm-property">prototype</span>.<span class="cm-property">teeth</span>);
<span class="cm-comment">// → small</span></pre>
<p><a class=p_ident id="p_HM5YtS3KgJ" href="#p_HM5YtS3KgJ"></a>The following diagram sketches the situation
after this code has run. The <code>Rabbit</code> and <code>Object</code> prototypes lie
behind <code>killerRabbit</code> as a kind of backdrop, where properties that are
not found in the object itself can be looked up.</p>
<div class="image">
<img src="img/rabbits.svg" alt="Rabbit object prototype schema">
</div>
<p><a class=p_ident id="p_or3/lz1DV8" href="#p_or3/lz1DV8"></a>Overriding properties that exist in a prototype
is often a useful thing to do. As the rabbit teeth example shows, it
can be used to express exceptional properties in instances of a more
generic class of objects, while letting the nonexceptional objects
simply take a standard value from their prototype.</p>
<p><a class=p_ident id="p_O8pyFABp7m" href="#p_O8pyFABp7m"></a>It
is also used to give the standard function and array prototypes a
different <code>toString</code> method than the basic object prototype.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_lQG1eSFUan" href="#c_lQG1eSFUan"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Array</span>.<span class="cm-property">prototype</span>.<span class="cm-property">toString</span> <span class="cm-operator">==</span>
<span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>.<span class="cm-property">toString</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">1</span>, <span class="cm-number">2</span>].<span class="cm-property">toString</span>());
<span class="cm-comment">// → 1,2</span></pre>
<p><a class=p_ident id="p_qmKAzHrRQG" href="#p_qmKAzHrRQG"></a>Calling
<code>toString</code> on an array gives a result similar to calling <code>.join(",")</code>
on it—it puts commas between the values in the array. Directly calling
<code>Object.prototype.toString</code> with an array produces a different string.
That function doesn’t know about arrays, so it simply puts the word
“object” and the name of the type between square brackets.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_74xTJFhRVW" href="#c_74xTJFhRVW"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>.<span class="cm-property">toString</span>.<span class="cm-property">call</span>([<span class="cm-number">1</span>, <span class="cm-number">2</span>]));
<span class="cm-comment">// → [object Array]</span></pre>
<h2><a class=h_ident id="h_QIL5obVMhZ" href="#h_QIL5obVMhZ"></a>Prototype interference</h2>
<p><a class=p_ident id="p_N34jQ1q+jC" href="#p_N34jQ1q+jC"></a>A
prototype can be used at any time to add new properties and
methods to all objects based on it. For example, it might become
necessary for our rabbits to dance.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_3EjiFcThqx" href="#c_3EjiFcThqx"></a><span class="cm-variable">Rabbit</span>.<span class="cm-property">prototype</span>.<span class="cm-property">dance</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"The "</span> <span class="cm-operator">+</span> <span class="cm-keyword">this</span>.<span class="cm-property">type</span> <span class="cm-operator">+</span> <span class="cm-string">" rabbit dances a jig."</span>);
};
<span class="cm-variable">killerRabbit</span>.<span class="cm-property">dance</span>();
<span class="cm-comment">// → The killer rabbit dances a jig.</span></pre>
<p><a class=p_ident id="p_U5nebQZlJ4" href="#p_U5nebQZlJ4"></a>That’s convenient. But there are
situations where it causes problems. In previous chapters, we used an
object as a way to associate values with names by creating properties
for the names and giving them the corresponding value as their value.
Here’s an example from <a href="04_data.html#object_map">Chapter 4</a>:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_mm9wdDpout" href="#c_mm9wdDpout"></a><span class="cm-keyword">var</span> <span class="cm-variable">map</span> <span class="cm-operator">=</span> {};
<span class="cm-keyword">function</span> <span class="cm-variable">storePhi</span>(<span class="cm-def">event</span>, <span class="cm-def">phi</span>) {
<span class="cm-variable">map</span>[<span class="cm-variable-2">event</span>] <span class="cm-operator">=</span> <span class="cm-variable-2">phi</span>;
}
<span class="cm-variable">storePhi</span>(<span class="cm-string">"pizza"</span>, <span class="cm-number">0.069</span>);
<span class="cm-variable">storePhi</span>(<span class="cm-string">"touched tree"</span>, <span class="cm-operator">-</span><span class="cm-number">0.081</span>);</pre>
<p><a class=p_ident id="p_FtECKQ2UPV" href="#p_FtECKQ2UPV"></a>We can iterate over all phi values
in the object using a <code>for</code>/<code>in</code> loop and test whether a name is in
there using the regular <code>in</code> operator. But unfortunately, the object’s
prototype gets in the way.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_OFbCsuDw4K" href="#c_OFbCsuDw4K"></a><span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>.<span class="cm-property">nonsense</span> <span class="cm-operator">=</span> <span class="cm-string">"hi"</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">name</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>)
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">name</span>);
<span class="cm-comment">// → pizza</span>
<span class="cm-comment">// → touched tree</span>
<span class="cm-comment">// → nonsense</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"nonsense"</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"toString"</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>);
<span class="cm-comment">// → true</span>
<span class="cm-comment">// Delete the problematic property again</span>
<span class="cm-keyword">delete</span> <span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>.<span class="cm-property">nonsense</span>;</pre>
<p><a class=p_ident id="p_xoSFOumlvj" href="#p_xoSFOumlvj"></a>That’s all wrong. There
is no event called “nonsense” in our data set. And there <em>definitely</em>
is no event called “toString”.</p>
<p><a class=p_ident id="p_NGyDSRSyjr" href="#p_NGyDSRSyjr"></a>Oddly, <code>toString</code>
did not show up in the <code>for</code>/<code>in</code> loop, but the <code>in</code> operator did
return true for it. This is because JavaScript distinguishes between
<em>enumerable</em> and <em>nonenumerable</em> properties.</p>
<p><a class=p_ident id="p_xfPTy1q4XS" href="#p_xfPTy1q4XS"></a>All properties that we create by simply
assigning to them are enumerable. The standard properties in
<code>Object.prototype</code> are all nonenumerable, which is why they do not
show up in such a <code>for</code>/<code>in</code> loop.</p>
<p><a class=p_ident id="p_sgLvQxcvMV" href="#p_sgLvQxcvMV"></a>It is possible to define our own
nonenumerable properties by using the <code>Object.defineProperty</code>
function, which allows us to control the type of property we are
creating.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_SiEdkjWs9U" href="#c_SiEdkjWs9U"></a><span class="cm-variable">Object</span>.<span class="cm-property">defineProperty</span>(<span class="cm-variable">Object</span>.<span class="cm-property">prototype</span>, <span class="cm-string">"hiddenNonsense"</span>,
{<span class="cm-property">enumerable</span>: <span class="cm-atom">false</span>, <span class="cm-property">value</span>: <span class="cm-string">"hi"</span>});
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">name</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>)
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">name</span>);
<span class="cm-comment">// → pizza</span>
<span class="cm-comment">// → touched tree</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">map</span>.<span class="cm-property">hiddenNonsense</span>);
<span class="cm-comment">// → hi</span></pre>
<p><a class=p_ident id="p_wMLrx6TIjh" href="#p_wMLrx6TIjh"></a>So now the property is there, but it won’t show up in a loop.
That’s good. But we still have the problem with the regular <code>in</code>
operator claiming that the <code>Object.prototype</code> properties exist in our
object. For that, we can use the object’s <code>hasOwnProperty</code> method.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_cKnuL5PvvB" href="#c_cKnuL5PvvB"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">map</span>.<span class="cm-property">hasOwnProperty</span>(<span class="cm-string">"toString"</span>));
<span class="cm-comment">// → false</span></pre>
<p><a class=p_ident id="p_1/lgWgImJc" href="#p_1/lgWgImJc"></a>This method tells us whether the object <em>itself</em> has
the property, without looking at its prototypes. This is often a more
useful piece of information than what the <code>in</code> operator gives us.</p>
<p><a class=p_ident id="p_BFvrJTamlf" href="#p_BFvrJTamlf"></a>When you are worried that
someone (some other code you loaded into your program) might have
messed with the base object prototype, I recommend you write your
<code>for</code>/<code>in</code> loops like this:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_KDS7ZDPuiN" href="#c_KDS7ZDPuiN"></a><span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">name</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>) {
<span class="cm-keyword">if</span> (<span class="cm-variable">map</span>.<span class="cm-property">hasOwnProperty</span>(<span class="cm-variable">name</span>)) {
<span class="cm-comment">// ... this is an own property</span>
}
}</pre>
<h2><a class=h_ident id="h_1vS5Ik5kV5" href="#h_1vS5Ik5kV5"></a>Prototype-less objects</h2>
<p><a class=p_ident id="p_kSmosu1+EH" href="#p_kSmosu1+EH"></a>But the
rabbit hole doesn’t end there. What if someone registered the name
<code>hasOwnProperty</code> in our <code>map</code> object and set it to the value 42? Now
the call to <code>map.hasOwnProperty</code> will try to call the local property,
which holds a number, not a function.</p>
<p><a class=p_ident id="p_tjlKDpfc75" href="#p_tjlKDpfc75"></a>In such a case,
prototypes just get in the way, and we would actually prefer to have
objects without prototypes. We saw the <code>Object.create</code> function, which
allows us to create an object with a specific prototype. You are
allowed to pass <code>null</code> as the prototype to create a fresh object with
no prototype. For objects like <code>map</code>, where the properties could be
anything, this is exactly what we want.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_NhO7nqeTuz" href="#c_NhO7nqeTuz"></a><span class="cm-keyword">var</span> <span class="cm-variable">map</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-atom">null</span>);
<span class="cm-variable">map</span>[<span class="cm-string">"pizza"</span>] <span class="cm-operator">=</span> <span class="cm-number">0.069</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"toString"</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"pizza"</span> <span class="cm-keyword">in</span> <span class="cm-variable">map</span>);
<span class="cm-comment">// → true</span></pre>
<p><a class=p_ident id="p_jKSTfVS3KH" href="#p_jKSTfVS3KH"></a>Much
better! We no longer need the <code>hasOwnProperty</code> kludge because all the
properties the object has are its own properties. Now we can safely
use <code>for</code>/<code>in</code> loops, no matter what people have been doing to
<code>Object.prototype</code>.</p>
<h2><a class=h_ident id="h_mJ/JHQRHg9" href="#h_mJ/JHQRHg9"></a>Polymorphism</h2>
<p><a class=p_ident id="p_+2Ates4jdf" href="#p_+2Ates4jdf"></a>When you call the
<code>String</code> function, which converts a value to a string, on an object,
it will call the <code>toString</code> method on that object to try to create a
meaningful string to return. I mentioned that some of the standard
prototypes define their own version of <code>toString</code> so they can
create a string that contains more useful information than
<code>"[object Object]"</code>.</p>
<p><a class=p_ident id="p_HgUFdFB6vM" href="#p_HgUFdFB6vM"></a>This is a simple instance of a
powerful idea. When a piece of code is written to work with objects
that have a certain interface—in this case, a <code>toString</code>
method—any kind of object that happens to support this interface can
be plugged into the code, and it will just work.</p>
<p><a class=p_ident id="p_phZ92zNL98" href="#p_phZ92zNL98"></a>This technique is called <em>polymorphism</em>—though no actual
shape-shifting is involved. Polymorphic code can work with values of
different shapes, as long as they support the interface it expects.</p>
<h2 id="tables"><a class=h_ident id="h_36C2FHHi44" href="#h_36C2FHHi44"></a>Laying out a table</h2>
<p><a class=p_ident id="p_nOQLqBWk1x" href="#p_nOQLqBWk1x"></a>I am going to work through
a slightly more involved example in an attempt to give you a better
idea what polymorphism, as well as object-oriented programming
in general, looks like. The project is this: we will write a program
that, given an array of arrays of table cells, builds up a string
that contains a nicely laid out table—meaning that the columns are
straight and the rows are aligned. Something like this:</p>
<pre data-language="text/plain" class="snippet cm-s-default"><a class=c_ident id="c_eMPUYfBonM" href="#c_eMPUYfBonM"></a>name height country
------------ ------ -------------
Kilimanjaro 5895 Tanzania
Everest 8848 Nepal
Mount Fuji 3776 Japan
Mont Blanc 4808 Italy/France
Vaalserberg 323 Netherlands
Denali 6168 United States
Popocatepetl 5465 Mexico</pre>
<p><a class=p_ident id="p_qmL/8YKol6" href="#p_qmL/8YKol6"></a>The way our table-building system will work is that the builder
function will ask each cell how wide and high it wants to be and then
use this information to determine the width of the columns and the
height of the rows. The builder function will then ask the cells to
draw themselves at the correct size and assemble the results into a
single string.</p>
<p id="table_interface"><a class=p_ident id="p_AbogVAH0Wj" href="#p_AbogVAH0Wj"></a>The layout program will communicate with the cell
objects through a well-defined interface. That way, the types of
cells that the program supports is not fixed in advance. We can add
new cell styles later—for example, underlined cells for table
headers—and if they support our interface, they will just work,
without requiring changes to the layout program.</p>
<p><a class=p_ident id="p_Oe6ruNqozx" href="#p_Oe6ruNqozx"></a>This is the interface:</p>
<div class="ulist"><ul>
<li>
<p><a class=p_ident id="p_/UA7VFmSpc" href="#p_/UA7VFmSpc"></a>
<code>minHeight()</code> returns a number indicating the minimum height this
cell requires (in lines).
</p>
</li>
<li>
<p><a class=p_ident id="p_92QZ/amzwk" href="#p_92QZ/amzwk"></a>
<code>minWidth()</code> returns a number indicating this cell’s minimum width (in
characters).
</p>
</li>
<li>
<p><a class=p_ident id="p_yx5zfEFlc0" href="#p_yx5zfEFlc0"></a>
<code>draw(width, height)</code> returns an array of length
<code>height</code>, which contains a series of strings that are each <code>width</code> characters wide.
This represents the content of the cell.
</p>
</li>
</ul></div>
<p><a class=p_ident id="p_26lYAjlPjb" href="#p_26lYAjlPjb"></a>I’m going to make heavy use of higher-order
array methods in this example since it lends itself well to that
approach.</p>
<p><a class=p_ident id="p_GckWQ2f1q/" href="#p_GckWQ2f1q/"></a>The first part of the program computes
arrays of minimum column widths and row heights for a grid of cells.
The <code>rows</code> variable will hold an array of arrays, with each inner array
representing a row of cells.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_1t+FkMSSZy" href="#c_1t+FkMSSZy"></a><span class="cm-keyword">function</span> <span class="cm-variable">rowHeights</span>(<span class="cm-def">rows</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">rows</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">row</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">row</span>.<span class="cm-property">reduce</span>(<span class="cm-keyword">function</span>(<span class="cm-def">max</span>, <span class="cm-def">cell</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">Math</span>.<span class="cm-property">max</span>(<span class="cm-variable-2">max</span>, <span class="cm-variable-2">cell</span>.<span class="cm-property">minHeight</span>());
}, <span class="cm-number">0</span>);
});
}
<span class="cm-keyword">function</span> <span class="cm-variable">colWidths</span>(<span class="cm-def">rows</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">rows</span>[<span class="cm-number">0</span>].<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">_</span>, <span class="cm-def">i</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">rows</span>.<span class="cm-property">reduce</span>(<span class="cm-keyword">function</span>(<span class="cm-def">max</span>, <span class="cm-def">row</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">Math</span>.<span class="cm-property">max</span>(<span class="cm-variable-2">max</span>, <span class="cm-variable-2">row</span>[<span class="cm-variable-2">i</span>].<span class="cm-property">minWidth</span>());
}, <span class="cm-number">0</span>);
});
}</pre>
<p><a class=p_ident id="p_tFp8Lj1YMr" href="#p_tFp8Lj1YMr"></a>Using a variable name
starting with an underscore (_) or consisting entirely of a single
underscore is a way to indicate (to human readers) that this argument
is not going to be used.</p>
<p><a class=p_ident id="p_LkGlygwwP+" href="#p_LkGlygwwP+"></a>The <code>rowHeights</code> function shouldn’t be too hard to follow. It uses
<code>reduce</code> to compute the maximum height of an array of cells and wraps
that in <code>map</code> in order to do it for all rows in the <code>rows</code> array.</p>
<p><a class=p_ident id="p_aeXoDNewFW" href="#p_aeXoDNewFW"></a>Things are slightly
harder for the <code>colWidths</code> function because the outer array is an
array of rows, not of columns. I have failed to mention so far that
<code>map</code> (as well as <code>forEach</code>, <code>filter</code>, and similar array methods)
passes a second argument to the function it is given: the index of
the current element. By mapping over the elements of the first row and
only using the mapping function’s second argument, <code>colWidths</code> builds
up an array with one element for every column index. The call to
<code>reduce</code> runs over the outer <code>rows</code> array for each index and picks
out the width of the widest cell at that index.</p>
<p><a class=p_ident id="p_/Tbz5eCViE" href="#p_/Tbz5eCViE"></a>Here’s the code to draw a
table:</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_vsR7akwib/" href="#c_vsR7akwib/"></a><span class="cm-keyword">function</span> <span class="cm-variable">drawTable</span>(<span class="cm-def">rows</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">heights</span> <span class="cm-operator">=</span> <span class="cm-variable">rowHeights</span>(<span class="cm-variable-2">rows</span>);
<span class="cm-keyword">var</span> <span class="cm-def">widths</span> <span class="cm-operator">=</span> <span class="cm-variable">colWidths</span>(<span class="cm-variable-2">rows</span>);
<span class="cm-keyword">function</span> <span class="cm-def">drawLine</span>(<span class="cm-def">blocks</span>, <span class="cm-def">lineNo</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">blocks</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">block</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">block</span>[<span class="cm-variable-2">lineNo</span>];
}).<span class="cm-property">join</span>(<span class="cm-string">" "</span>);
}
<span class="cm-keyword">function</span> <span class="cm-def">drawRow</span>(<span class="cm-def">row</span>, <span class="cm-def">rowNum</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">blocks</span> <span class="cm-operator">=</span> <span class="cm-variable-2">row</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">cell</span>, <span class="cm-def">colNum</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">cell</span>.<span class="cm-property">draw</span>(<span class="cm-variable-2">widths</span>[<span class="cm-variable-2">colNum</span>], <span class="cm-variable-2">heights</span>[<span class="cm-variable-2">rowNum</span>]);
});
<span class="cm-keyword">return</span> <span class="cm-variable-2">blocks</span>[<span class="cm-number">0</span>].<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">_</span>, <span class="cm-def">lineNo</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">drawLine</span>(<span class="cm-variable-2">blocks</span>, <span class="cm-variable-2">lineNo</span>);
}).<span class="cm-property">join</span>(<span class="cm-string">"\n"</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">rows</span>.<span class="cm-property">map</span>(<span class="cm-variable-2">drawRow</span>).<span class="cm-property">join</span>(<span class="cm-string">"\n"</span>);
}</pre>
<p><a class=p_ident id="p_QSCDyHczZF" href="#p_QSCDyHczZF"></a>The <code>drawTable</code> function
uses the internal helper function <code>drawRow</code> to draw all rows and then
joins them together with newline characters.</p>
<p><a class=p_ident id="p_b8wKD7NyzT" href="#p_b8wKD7NyzT"></a>The <code>drawRow</code> function itself first converts the
cell objects in the row to <em>blocks</em>, which are arrays of strings
representing the content of the cells, split by line. A single cell
containing simply the number 3776 might be represented by a
single-element array like <code>["3776"]</code>, whereas an underlined cell might
take up two lines and be represented by the array <code>["name", "----"]</code>.</p>
<p><a class=p_ident id="p_uYZRAIhAHn" href="#p_uYZRAIhAHn"></a>The blocks for a row, which all have
the same height, should appear next to each other in the final output.
The second call to <code>map</code> in <code>drawRow</code> builds up this output line by
line by mapping over the lines in the leftmost block and, for each of
those, collecting a line that spans the full width of the table. These
lines are then joined with newline characters to provide the whole row
as <code>drawRow</code>’s return value.</p>
<p><a class=p_ident id="p_1AKETNclQn" href="#p_1AKETNclQn"></a>The function <code>drawLine</code> extracts lines that should appear next
to each other from an array of blocks and joins them with a space
character to create a one-character gap between the table’s columns.</p>
<p id="split"><a class=p_ident id="p_bbKpGggVOW" href="#p_bbKpGggVOW"></a>Now
let’s write a constructor for cells that contain text, which
implements the interface for table cells. The constructor splits a
string into an array of lines using the string method <code>split</code>, which
cuts up a string at every occurrence of its argument and returns an
array of the pieces. The <code>minWidth</code> method finds the maximum line
width in this array.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_7NDpmoh43p" href="#c_7NDpmoh43p"></a><span class="cm-keyword">function</span> <span class="cm-variable">repeat</span>(<span class="cm-def">string</span>, <span class="cm-def">times</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">result</span> <span class="cm-operator">=</span> <span class="cm-string">""</span>;
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable-2">i</span> <span class="cm-operator"><</span> <span class="cm-variable-2">times</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>)
<span class="cm-variable-2">result</span> <span class="cm-operator">+=</span> <span class="cm-variable-2">string</span>;
<span class="cm-keyword">return</span> <span class="cm-variable-2">result</span>;
}
<span class="cm-keyword">function</span> <span class="cm-variable">TextCell</span>(<span class="cm-def">text</span>) {
<span class="cm-keyword">this</span>.<span class="cm-property">text</span> <span class="cm-operator">=</span> <span class="cm-variable-2">text</span>.<span class="cm-property">split</span>(<span class="cm-string">"\n"</span>);
}
<span class="cm-variable">TextCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">minWidth</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">text</span>.<span class="cm-property">reduce</span>(<span class="cm-keyword">function</span>(<span class="cm-def">width</span>, <span class="cm-def">line</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable">Math</span>.<span class="cm-property">max</span>(<span class="cm-variable-2">width</span>, <span class="cm-variable-2">line</span>.<span class="cm-property">length</span>);
}, <span class="cm-number">0</span>);
};
<span class="cm-variable">TextCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">minHeight</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">text</span>.<span class="cm-property">length</span>;
};
<span class="cm-variable">TextCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">draw</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">width</span>, <span class="cm-def">height</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">result</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable-2">i</span> <span class="cm-operator"><</span> <span class="cm-variable-2">height</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">line</span> <span class="cm-operator">=</span> <span class="cm-keyword">this</span>.<span class="cm-property">text</span>[<span class="cm-variable-2">i</span>] <span class="cm-operator">||</span> <span class="cm-string">""</span>;
<span class="cm-variable-2">result</span>.<span class="cm-property">push</span>(<span class="cm-variable-2">line</span> <span class="cm-operator">+</span> <span class="cm-variable">repeat</span>(<span class="cm-string">" "</span>, <span class="cm-variable-2">width</span> <span class="cm-operator">-</span> <span class="cm-variable-2">line</span>.<span class="cm-property">length</span>));
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">result</span>;
};</pre>
<p><a class=p_ident id="p_XqC4cWwgYI" href="#p_XqC4cWwgYI"></a>The code uses a helper function called <code>repeat</code>,
which builds a string whose value is the <code>string</code> argument repeated
<code>times</code> number of times. The <code>draw</code> method uses it to add “padding” to
lines so that they all have the required length.</p>
<p><a class=p_ident id="p_4T1Kk1qpd9" href="#p_4T1Kk1qpd9"></a>Let’s try everything we’ve written so far by building up a 5 × 5
checkerboard.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_KZr3Gjzueh" href="#c_KZr3Gjzueh"></a><span class="cm-keyword">var</span> <span class="cm-variable">rows</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">i</span> <span class="cm-operator"><</span> <span class="cm-number">5</span>; <span class="cm-variable">i</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">var</span> <span class="cm-variable">row</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-variable">j</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable">j</span> <span class="cm-operator"><</span> <span class="cm-number">5</span>; <span class="cm-variable">j</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">if</span> ((<span class="cm-variable">j</span> <span class="cm-operator">+</span> <span class="cm-variable">i</span>) <span class="cm-operator">%</span> <span class="cm-number">2</span> <span class="cm-operator">==</span> <span class="cm-number">0</span>)
<span class="cm-variable">row</span>.<span class="cm-property">push</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-string">"##"</span>));
<span class="cm-keyword">else</span>
<span class="cm-variable">row</span>.<span class="cm-property">push</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-string">" "</span>));
}
<span class="cm-variable">rows</span>.<span class="cm-property">push</span>(<span class="cm-variable">row</span>);
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">drawTable</span>(<span class="cm-variable">rows</span>));
<span class="cm-comment">// → ## ## ##</span>
<span class="cm-comment">// ## ##</span>
<span class="cm-comment">// ## ## ##</span>
<span class="cm-comment">// ## ##</span>
<span class="cm-comment">// ## ## ##</span></pre>
<p><a class=p_ident id="p_ZlgwbD41JK" href="#p_ZlgwbD41JK"></a>It works! But since all cells have the same size, the table-layout
code doesn’t really do anything interesting.</p>
<p id="mountains"><a class=p_ident id="p_ziLMS9iu5Y" href="#p_ziLMS9iu5Y"></a>The source data for the table of
mountains that we are trying to build is available in the <code>MOUNTAINS</code>
variable in the sandbox and also
<a href="http://eloquentjavascript.net/code/mountains.js">downloadable</a> from the
website.</p>
<p><a class=p_ident id="p_UiCC/VFl9F" href="#p_UiCC/VFl9F"></a>We will want to highlight the top row, which
contains the column names, by underlining the cells with a series of
dash characters. No problem—we simply write a cell type that handles
underlining.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_+e6Xt5s1Yy" href="#c_+e6Xt5s1Yy"></a><span class="cm-keyword">function</span> <span class="cm-variable">UnderlinedCell</span>(<span class="cm-def">inner</span>) {
<span class="cm-keyword">this</span>.<span class="cm-property">inner</span> <span class="cm-operator">=</span> <span class="cm-variable-2">inner</span>;
}
<span class="cm-variable">UnderlinedCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">minWidth</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">inner</span>.<span class="cm-property">minWidth</span>();
};
<span class="cm-variable">UnderlinedCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">minHeight</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">inner</span>.<span class="cm-property">minHeight</span>() <span class="cm-operator">+</span> <span class="cm-number">1</span>;
};
<span class="cm-variable">UnderlinedCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">draw</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">width</span>, <span class="cm-def">height</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">inner</span>.<span class="cm-property">draw</span>(<span class="cm-variable-2">width</span>, <span class="cm-variable-2">height</span> <span class="cm-operator">-</span> <span class="cm-number">1</span>)
.<span class="cm-property">concat</span>([<span class="cm-variable">repeat</span>(<span class="cm-string">"-"</span>, <span class="cm-variable-2">width</span>)]);
};</pre>
<p><a class=p_ident id="p_1VGPKHtYoJ" href="#p_1VGPKHtYoJ"></a>An underlined cell <em>contains</em> another cell.
It reports its minimum size as being the same as that of its inner
cell (by calling through to that cell’s <code>minWidth</code> and <code>minHeight</code>
methods) but adds one to the height to account for the space taken
up by the underline.</p>
<p><a class=p_ident id="p_9oFg/rPQCi" href="#p_9oFg/rPQCi"></a>Drawing such a cell is quite
simple—we take the content of the inner cell and concatenate a single
line full of dashes to it.</p>
<p><a class=p_ident id="p_e8CuToYm1C" href="#p_e8CuToYm1C"></a>Having an underlining mechanism, we can now
write a function that builds up a grid of cells from our data set.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_D7Pdre4OZl" href="#c_D7Pdre4OZl"></a><span class="cm-keyword">function</span> <span class="cm-variable">dataTable</span>(<span class="cm-def">data</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">keys</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">keys</span>(<span class="cm-variable-2">data</span>[<span class="cm-number">0</span>]);
<span class="cm-keyword">var</span> <span class="cm-def">headers</span> <span class="cm-operator">=</span> <span class="cm-variable-2">keys</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">name</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">UnderlinedCell</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-variable-2">name</span>));
});
<span class="cm-keyword">var</span> <span class="cm-def">body</span> <span class="cm-operator">=</span> <span class="cm-variable-2">data</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">row</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">keys</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">name</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-variable">String</span>(<span class="cm-variable-2">row</span>[<span class="cm-variable-2">name</span>]));
});
});
<span class="cm-keyword">return</span> [<span class="cm-variable-2">headers</span>].<span class="cm-property">concat</span>(<span class="cm-variable-2">body</span>);
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">drawTable</span>(<span class="cm-variable">dataTable</span>(<span class="cm-variable">MOUNTAINS</span>)));
<span class="cm-comment">// → name height country</span>
<span class="cm-comment">// ------------ ------ -------------</span>
<span class="cm-comment">// Kilimanjaro 5895 Tanzania</span>
<span class="cm-comment">// … etcetera</span></pre>
<p id="keys"><a class=p_ident id="p_cv0EdFlmx8" href="#p_cv0EdFlmx8"></a>The standard
<code>Object.keys</code> function returns an array of property names in an
object. The top row of the table must contain underlined cells that
give the names of the columns. Below that, the values of all the
objects in the data set appear as normal cells—we extract them by
mapping over the <code>keys</code> array so that we are sure that the order of
the cells is the same in every row.</p>
<p><a class=p_ident id="p_8Kn9AmEQyS" href="#p_8Kn9AmEQyS"></a>The resulting table resembles the example shown
before, except that it does not right-align the numbers in the
<code>height</code> column. We will get to that in a moment.</p>
<h2><a class=h_ident id="h_Kd3nnpSvTd" href="#h_Kd3nnpSvTd"></a>Getters and setters</h2>
<p><a class=p_ident id="p_nkLul78hk8" href="#p_nkLul78hk8"></a>When specifying an interface, it
is possible to include properties that are not methods. We could have
defined <code>minHeight</code> and <code>minWidth</code> to simply hold numbers. But that’d
have required us to compute them in the constructor, which adds
code there that isn’t strictly relevant to <em>constructing</em> the object.
It would cause problems if, for example, the inner cell of an
underlined cell was changed, at which point the size of the underlined
cell should also change.</p>
<p><a class=p_ident id="p_U+A3uiYe5T" href="#p_U+A3uiYe5T"></a>This has led some people to adopt a principle
of never including nonmethod properties in interfaces. Rather than
directly access a simple value property, they’d use <code>getSomething</code> and
<code>setSomething</code> methods to read and write the property. This approach
has the downside that you will end up writing—and reading—a lot of
additional methods.</p>
<p><a class=p_ident id="p_SkpjeeWsdC" href="#p_SkpjeeWsdC"></a>Fortunately, JavaScript provides a technique that gets us the best of
both worlds. We can specify properties that, from the outside, look
like normal properties but secretly have methods associated with
them.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_ntMbCYFmyG" href="#c_ntMbCYFmyG"></a><span class="cm-keyword">var</span> <span class="cm-variable">pile</span> <span class="cm-operator">=</span> {
<span class="cm-property">elements</span>: [<span class="cm-string">"eggshell"</span>, <span class="cm-string">"orange peel"</span>, <span class="cm-string">"worm"</span>],
<span class="cm-property">get</span> <span class="cm-property">height</span>() {
<span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">elements</span>.<span class="cm-property">length</span>;
},
<span class="cm-property">set</span> <span class="cm-property">height</span>(<span class="cm-def">value</span>) {
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-string">"Ignoring attempt to set height to"</span>, <span class="cm-variable-2">value</span>);
}
};
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">pile</span>.<span class="cm-property">height</span>);
<span class="cm-comment">// → 3</span>
<span class="cm-variable">pile</span>.<span class="cm-property">height</span> <span class="cm-operator">=</span> <span class="cm-number">100</span>;
<span class="cm-comment">// → Ignoring attempt to set height to 100</span></pre>
<p><a class=p_ident id="p_av+X6VQ/sQ" href="#p_av+X6VQ/sQ"></a>In object literal, the <code>get</code> or
<code>set</code> notation for properties allows you to specify a function to be
run when the property is read or written. You can also add such a
property to an existing object, for example a prototype, using the
<code>Object.defineProperty</code> function (which we previously used to create
nonenumerable properties).</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_cIP0PL5CZB" href="#c_cIP0PL5CZB"></a><span class="cm-variable">Object</span>.<span class="cm-property">defineProperty</span>(<span class="cm-variable">TextCell</span>.<span class="cm-property">prototype</span>, <span class="cm-string">"heightProp"</span>, {
<span class="cm-property">get</span>: <span class="cm-keyword">function</span>() { <span class="cm-keyword">return</span> <span class="cm-keyword">this</span>.<span class="cm-property">text</span>.<span class="cm-property">length</span>; }
});
<span class="cm-keyword">var</span> <span class="cm-variable">cell</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-string">"no\nway"</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">cell</span>.<span class="cm-property">heightProp</span>);
<span class="cm-comment">// → 2</span>
<span class="cm-variable">cell</span>.<span class="cm-property">heightProp</span> <span class="cm-operator">=</span> <span class="cm-number">100</span>;
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">cell</span>.<span class="cm-property">heightProp</span>);
<span class="cm-comment">// → 2</span></pre>
<p><a class=p_ident id="p_g533VU/mhK" href="#p_g533VU/mhK"></a>You can use a similar <code>set</code> property, in the object passed to
<code>defineProperty</code>, to specify a setter method. When a getter but no
setter is defined, writing to the property is simply ignored.</p>
<h2><a class=h_ident id="h_/a3bnONnws" href="#h_/a3bnONnws"></a>Inheritance</h2>
<p><a class=p_ident id="p_pcw8AFLxa1" href="#p_pcw8AFLxa1"></a>We are not quite done yet with our table layout exercise. It
helps readability to right-align columns of numbers. We should create
another cell type that is like <code>TextCell</code>, but rather than padding the
lines on the right side, it pads them on the left side so that they
align to the right.</p>
<p><a class=p_ident id="p_ozN/QrVH/c" href="#p_ozN/QrVH/c"></a>We could simply write a whole new constructor
with all three methods in its prototype. But prototypes may themselves
have prototypes, and this allows us to do something clever.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_IZO3vruzSN" href="#c_IZO3vruzSN"></a><span class="cm-keyword">function</span> <span class="cm-variable">RTextCell</span>(<span class="cm-def">text</span>) {
<span class="cm-variable">TextCell</span>.<span class="cm-property">call</span>(<span class="cm-keyword">this</span>, <span class="cm-variable-2">text</span>);
}
<span class="cm-variable">RTextCell</span>.<span class="cm-property">prototype</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">create</span>(<span class="cm-variable">TextCell</span>.<span class="cm-property">prototype</span>);
<span class="cm-variable">RTextCell</span>.<span class="cm-property">prototype</span>.<span class="cm-property">draw</span> <span class="cm-operator">=</span> <span class="cm-keyword">function</span>(<span class="cm-def">width</span>, <span class="cm-def">height</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">result</span> <span class="cm-operator">=</span> [];
<span class="cm-keyword">for</span> (<span class="cm-keyword">var</span> <span class="cm-def">i</span> <span class="cm-operator">=</span> <span class="cm-number">0</span>; <span class="cm-variable-2">i</span> <span class="cm-operator"><</span> <span class="cm-variable-2">height</span>; <span class="cm-variable-2">i</span><span class="cm-operator">++</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">line</span> <span class="cm-operator">=</span> <span class="cm-keyword">this</span>.<span class="cm-property">text</span>[<span class="cm-variable-2">i</span>] <span class="cm-operator">||</span> <span class="cm-string">""</span>;
<span class="cm-variable-2">result</span>.<span class="cm-property">push</span>(<span class="cm-variable">repeat</span>(<span class="cm-string">" "</span>, <span class="cm-variable-2">width</span> <span class="cm-operator">-</span> <span class="cm-variable-2">line</span>.<span class="cm-property">length</span>) <span class="cm-operator">+</span> <span class="cm-variable-2">line</span>);
}
<span class="cm-keyword">return</span> <span class="cm-variable-2">result</span>;
};</pre>
<p><a class=p_ident id="p_+8Q1+4H5LI" href="#p_+8Q1+4H5LI"></a>We reuse the
constructor and the <code>minHeight</code> and <code>minWidth</code> methods from the
regular <code>TextCell</code>. An <code>RTextCell</code> is now basically equivalent to a
<code>TextCell</code>, except that its <code>draw</code> method contains a different
function.</p>
<p><a class=p_ident id="p_hncaW/95ov" href="#p_hncaW/95ov"></a>This pattern is called <em>inheritance</em>. It allows
us to build slightly different data types from existing data types with
relatively little work. Typically, the new constructor will call the
old constructor (using the <code>call</code> method in order to be able to
give it the new object as its <code>this</code> value). Once this constructor has
been called, we can assume that all the fields that the old object
type is supposed to contain have been added. We arrange for the
constructor’s prototype to derive from the old prototype so that
instances of this type will also have access to the properties in that
prototype. Finally, we can override some of these properties by adding
them to our new prototype.</p>
<p><a class=p_ident id="p_EcSCrpVw4N" href="#p_EcSCrpVw4N"></a>Now, if we slightly adjust the <code>dataTable</code>
function to use <code>RTextCell</code>s for cells whose value is a number, we
get the table we were aiming for.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_1S9JP3tD2k" href="#c_1S9JP3tD2k"></a><span class="cm-keyword">function</span> <span class="cm-variable">dataTable</span>(<span class="cm-def">data</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">keys</span> <span class="cm-operator">=</span> <span class="cm-variable">Object</span>.<span class="cm-property">keys</span>(<span class="cm-variable-2">data</span>[<span class="cm-number">0</span>]);
<span class="cm-keyword">var</span> <span class="cm-def">headers</span> <span class="cm-operator">=</span> <span class="cm-variable-2">keys</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">name</span>) {
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">UnderlinedCell</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-variable-2">name</span>));
});
<span class="cm-keyword">var</span> <span class="cm-def">body</span> <span class="cm-operator">=</span> <span class="cm-variable-2">data</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">row</span>) {
<span class="cm-keyword">return</span> <span class="cm-variable-2">keys</span>.<span class="cm-property">map</span>(<span class="cm-keyword">function</span>(<span class="cm-def">name</span>) {
<span class="cm-keyword">var</span> <span class="cm-def">value</span> <span class="cm-operator">=</span> <span class="cm-variable-2">row</span>[<span class="cm-variable-2">name</span>];
<span class="cm-comment">// This was changed:</span>
<span class="cm-keyword">if</span> (<span class="cm-keyword">typeof</span> <span class="cm-variable-2">value</span> <span class="cm-operator">==</span> <span class="cm-string">"number"</span>)
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">RTextCell</span>(<span class="cm-variable">String</span>(<span class="cm-variable-2">value</span>));
<span class="cm-keyword">else</span>
<span class="cm-keyword">return</span> <span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-variable">String</span>(<span class="cm-variable-2">value</span>));
});
});
<span class="cm-keyword">return</span> [<span class="cm-variable-2">headers</span>].<span class="cm-property">concat</span>(<span class="cm-variable-2">body</span>);
}
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">drawTable</span>(<span class="cm-variable">dataTable</span>(<span class="cm-variable">MOUNTAINS</span>)));
<span class="cm-comment">// → … beautifully aligned table</span></pre>
<p><a class=p_ident id="p_XiWor+mk9j" href="#p_XiWor+mk9j"></a>Inheritance is a fundamental part of
the object-oriented tradition, alongside encapsulation and
polymorphism. But while the latter two are now generally regarded as
wonderful ideas, inheritance is somewhat controversial.</p>
<p><a class=p_ident id="p_Q82/17hIfZ" href="#p_Q82/17hIfZ"></a>The main reason for this is that it is often confused
with polymorphism, sold as a more powerful tool than it really
is, and subsequently overused in all kinds of ugly ways. Whereas
encapsulation and polymorphism can be used to <em>separate</em> pieces of
code from each other, reducing the tangledness of the overall program,
inheritance fundamentally ties types together, creating <em>more</em>
tangle.</p>
<p><a class=p_ident id="p_jis0SWYeNY" href="#p_jis0SWYeNY"></a>You can have
polymorphism without inheritance, as we saw. I am not going to tell
you to avoid inheritance entirely—I use it regularly in my own
programs. But you should see it as a slightly dodgy trick that can help you
define new types with little code, not as a grand principle of code
organization. A preferable way to extend types is through
composition, such as how <code>UnderlinedCell</code> builds on another cell
object by simply storing it in a property and forwarding method calls
to it in its own methods.</p>
<h2><a class=h_ident id="h_Fdk67dJHwg" href="#h_Fdk67dJHwg"></a>The instanceof operator</h2>
<p><a class=p_ident id="p_j4pk5Qzlwd" href="#p_j4pk5Qzlwd"></a>It is occasionally useful to know whether an object was derived
from a specific constructor. For this, JavaScript provides a binary
operator called <code>instanceof</code>.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_3YbTJpj72O" href="#c_3YbTJpj72O"></a><span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">RTextCell</span>(<span class="cm-string">"A"</span>) <span class="cm-keyword">instanceof</span> <span class="cm-variable">RTextCell</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">RTextCell</span>(<span class="cm-string">"A"</span>) <span class="cm-keyword">instanceof</span> <span class="cm-variable">TextCell</span>);
<span class="cm-comment">// → true</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-string">"A"</span>) <span class="cm-keyword">instanceof</span> <span class="cm-variable">RTextCell</span>);
<span class="cm-comment">// → false</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>([<span class="cm-number">1</span>] <span class="cm-keyword">instanceof</span> <span class="cm-variable">Array</span>);
<span class="cm-comment">// → true</span></pre>
<p><a class=p_ident id="p_o+ZFEn1oZl" href="#p_o+ZFEn1oZl"></a>The operator will see through inherited types.
An <code>RTextCell</code> is an instance of <code>TextCell</code> because
<code>RTextCell.prototype</code> derives from <code>TextCell.prototype</code>. The operator
can be applied to standard constructors like <code>Array</code>. Almost every
object is an instance of <code>Object</code>.</p>
<h2><a class=h_ident id="h_ErccPg/l98" href="#h_ErccPg/l98"></a>Summary</h2>
<p><a class=p_ident id="p_StNbsy1mmY" href="#p_StNbsy1mmY"></a>So objects are more complicated than I initially portrayed them. They
have prototypes, which are other objects, and will act as if they have
properties they don’t have as long as the prototype has that property.
Simple objects have <code>Object.prototype</code> as their prototype.</p>
<p><a class=p_ident id="p_qMN9iu/ELN" href="#p_qMN9iu/ELN"></a>Constructors, which are functions whose names usually start with a
capital letter, can be used with the <code>new</code> operator to create new
objects. The new object’s prototype will be the object found in the
<code>prototype</code> property of the constructor function. You can make good
use of this by putting the properties that all values of a given type
share into their prototype. The <code>instanceof</code> operator can, given an
object and a constructor, tell you whether that object is an instance
of that constructor.</p>
<p><a class=p_ident id="p_zzr1L1PppY" href="#p_zzr1L1PppY"></a>One useful thing to do with objects is to specify an interface for
them and tell everybody that they are supposed to talk to your
object only through that interface. The rest of the details that make up
your object are now <em>encapsulated</em>, hidden behind the interface.</p>
<p><a class=p_ident id="p_5POqDFEqYS" href="#p_5POqDFEqYS"></a>Once you are talking in terms of interfaces, who says that only one
kind of object may implement this interface? Having different objects
expose the same interface and then writing code that works on any
object with the interface is called <em>polymorphism</em>. It is very
useful.</p>
<p><a class=p_ident id="p_9dzDvJ4kxT" href="#p_9dzDvJ4kxT"></a>When implementing multiple types that differ in only some details, it
can be helpful to simply make the prototype of your new type derive
from the prototype of your old type and have your new constructor
call the old one. This gives you an object type similar to the
old type but for which you can add and override properties as you see
fit.</p>
<h2><a class=h_ident id="h_TcUD2vzyMe" href="#h_TcUD2vzyMe"></a>Exercises</h2>
<h3 id="exercise_vector"><a class=h_ident id="h_zO8FRQBMAy" href="#h_zO8FRQBMAy"></a>A vector type</h3>
<p><a class=p_ident id="p_/6RUkCsOAv" href="#p_/6RUkCsOAv"></a>Write a
constructor <code>Vector</code> that represents a vector in two-dimensional
space. It takes <code>x</code> and <code>y</code> parameters (numbers), which it should save
to properties of the same name.</p>
<p><a class=p_ident id="p_smri4stKuh" href="#p_smri4stKuh"></a>Give the <code>Vector</code> prototype two
methods, <code>plus</code> and <code>minus</code>, that take another vector as a parameter
and return a new vector that has the sum or difference of the two
vectors’ (the one in <code>this</code> and the parameter) <em>x</em> and <em>y</em> values.</p>
<p><a class=p_ident id="p_F5nP+jpza3" href="#p_F5nP+jpza3"></a>Add a getter property <code>length</code> to the prototype that computes the
length of the vector—that is, the distance of the point (<em>x</em>, <em>y</em>) from
the origin (0, 0).</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_6ArTbGu09l" href="#c_6ArTbGu09l"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">Vector</span>(<span class="cm-number">1</span>, <span class="cm-number">2</span>).<span class="cm-property">plus</span>(<span class="cm-keyword">new</span> <span class="cm-variable">Vector</span>(<span class="cm-number">2</span>, <span class="cm-number">3</span>)));
<span class="cm-comment">// → Vector{x: 3, y: 5}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">Vector</span>(<span class="cm-number">1</span>, <span class="cm-number">2</span>).<span class="cm-property">minus</span>(<span class="cm-keyword">new</span> <span class="cm-variable">Vector</span>(<span class="cm-number">2</span>, <span class="cm-number">3</span>)));
<span class="cm-comment">// → Vector{x: -1, y: -1}</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-keyword">new</span> <span class="cm-variable">Vector</span>(<span class="cm-number">3</span>, <span class="cm-number">4</span>).<span class="cm-property">length</span>);
<span class="cm-comment">// → 5</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_92t0jiHPOP" href="#p_92t0jiHPOP"></a>Your solution can follow the pattern of the
<code>Rabbit</code> constructor from this chapter quite closely.</p>
<p><a class=p_ident id="p_9pw44RYeg9" href="#p_9pw44RYeg9"></a>Adding a getter property to the
constructor can be done with the <code>Object.defineProperty</code> function. To
compute the distance from (0, 0) to (x, y), you can use the
Pythagorean theorem, which says that the square of the distance we are
looking for is equal to the square of the x-coordinate plus the square
of the y-coordinate. Thus, √(x<sup>2</sup> + y<sup>2</sup>)
is the number you want, and <code>Math.sqrt</code> is the way you compute a square
root in JavaScript.</p>
</div></div>
<h3><a class=h_ident id="h_nLNNevzcF7" href="#h_nLNNevzcF7"></a>Another cell</h3>
<p><a class=p_ident id="p_fkvt0g2UPk" href="#p_fkvt0g2UPk"></a>Implement a cell type named
<code>StretchCell(inner, width, height)</code> that conforms to the
<a href="06_object.html#table_interface">table cell interface</a> described
earlier in the chapter. It should wrap another cell (like
<code>UnderlinedCell</code> does) and ensure that the resulting cell has at
least the given <code>width</code> and <code>height</code>, even if the inner cell would
naturally be smaller.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_jmfd83vFd2" href="#c_jmfd83vFd2"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-keyword">var</span> <span class="cm-variable">sc</span> <span class="cm-operator">=</span> <span class="cm-keyword">new</span> <span class="cm-variable">StretchCell</span>(<span class="cm-keyword">new</span> <span class="cm-variable">TextCell</span>(<span class="cm-string">"abc"</span>), <span class="cm-number">1</span>, <span class="cm-number">2</span>);
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sc</span>.<span class="cm-property">minWidth</span>());
<span class="cm-comment">// → 3</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sc</span>.<span class="cm-property">minHeight</span>());
<span class="cm-comment">// → 2</span>
<span class="cm-variable">console</span>.<span class="cm-property">log</span>(<span class="cm-variable">sc</span>.<span class="cm-property">draw</span>(<span class="cm-number">3</span>, <span class="cm-number">2</span>));
<span class="cm-comment">// → ["abc", " "]</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_YA/P+rsyIP" href="#p_YA/P+rsyIP"></a>You’ll have to store all three constructor
arguments in the instance object. The <code>minWidth</code> and <code>minHeight</code>
methods should call through to the corresponding methods in the
<code>inner</code> cell but ensure that no number less than the given size is
returned (possibly using <code>Math.max</code>).</p>
<p><a class=p_ident id="p_dHbeqBDeSx" href="#p_dHbeqBDeSx"></a>Don’t forget to add a <code>draw</code> method that simply forwards the call to
the inner cell.</p>
</div></div>
<h3><a class=h_ident id="h_a0w19Kx5iq" href="#h_a0w19Kx5iq"></a>Sequence interface</h3>
<p><a class=p_ident id="p_zIiyP1YArp" href="#p_zIiyP1YArp"></a>Design an <em>interface</em> that abstracts
iteration over a collection of values. An object that provides
this interface represents a sequence, and the interface must somehow
make it possible for code that uses such an object to iterate over the
sequence, looking at the element values it is made up of and having
some way to find out when the end of the sequence is reached.</p>
<p><a class=p_ident id="p_n9mbvCSpi+" href="#p_n9mbvCSpi+"></a>When you have specified your interface, try to write a function
<code>logFive</code> that takes a sequence object and calls <code>console.log</code> on its
first five elements—or fewer, if the sequence has fewer than five
elements.</p>
<p><a class=p_ident id="p_8fIkJ9NfIu" href="#p_8fIkJ9NfIu"></a>Then implement an object type <code>ArraySeq</code> that wraps an array and
allows iteration over the array using the interface you designed.
Implement another object type <code>RangeSeq</code> that iterates over a range of
integers (taking <code>from</code> and <code>to</code> arguments to its constructor)
instead.</p>
<pre data-language="javascript" class="snippet cm-s-default"><a class=c_ident id="c_RtuZFzccp9" href="#c_RtuZFzccp9"></a><span class="cm-comment">// Your code here.</span>
<span class="cm-variable">logFive</span>(<span class="cm-keyword">new</span> <span class="cm-variable">ArraySeq</span>([<span class="cm-number">1</span>, <span class="cm-number">2</span>]));
<span class="cm-comment">// → 1</span>
<span class="cm-comment">// → 2</span>
<span class="cm-variable">logFive</span>(<span class="cm-keyword">new</span> <span class="cm-variable">RangeSeq</span>(<span class="cm-number">100</span>, <span class="cm-number">1000</span>));
<span class="cm-comment">// → 100</span>
<span class="cm-comment">// → 101</span>
<span class="cm-comment">// → 102</span>
<span class="cm-comment">// → 103</span>
<span class="cm-comment">// → 104</span></pre>
<div class=solution><div class=solution-text>
<p><a class=p_ident id="p_mGNHzWPOz6" href="#p_mGNHzWPOz6"></a>One way to solve this is to
give the sequence objects <em>state</em>, meaning their properties are
changed in the process of using them. You could store a counter that
indicates how far the sequence object has advanced.</p>
<p><a class=p_ident id="p_XeygOj1rUp" href="#p_XeygOj1rUp"></a>Your interface will need to expose at least a way to get the next
element and to find out whether the iteration has reached the end of
the sequence yet. It is tempting to roll these into one method,
<code>next</code>, which returns <code>null</code> or <code>undefined</code> when the sequence is at
its end. But now you have a problem when a sequence actually contains
<code>null</code>. So a separate method (or getter property) to find out whether
the end has been reached is probably preferable.</p>
<p><a class=p_ident id="p_5ZGAXiv2dh" href="#p_5ZGAXiv2dh"></a>Another solution is
to avoid changing state in the object. You can expose a method for
getting the current element (without advancing any counter) and
another for getting a new sequence that represents the remaining
elements after the current one (or a special value if the end of the
sequence is reached). This is quite elegant—a sequence value will
“stay itself” even after it is used and can thus be shared with other
code without worrying about what might happen to it. It is,
unfortunately, also somewhat inefficient in a language like
JavaScript because it involves creating a lot of objects during
iteration.</p>
</div></div>
<nav>
<a href="05_higher_order.html" title="previous chapter">◀</a>
<a href="index.html" title="cover">◆</a>
<a href="07_elife.html" title="next chapter">▶</a>
</nav>
</article>