forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_object.txt
1222 lines (1014 loc) · 42.4 KB
/
06_object.txt
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
:chap_num: 6
:prev_link: 05_higher_order
:next_link: 07_elife
:load_files: ["code/mountains.js", "code/chapter/06_object.js"]
:zip: node/html
= The Secret Life of Objects =
[chapterquote="true"]
[quote, Joe Armstrong, interviewed in Coders at Work]
____
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.
____
(((Armstrong+++,+++ Joe)))(((object)))(((holy war)))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.
To an outsider, this is probably a little confusing. Let's start with
a brief ((history)) of objects as a programming construct.
== History ==
(((isolation)))(((history)))(((object-oriented programming)))(((object)))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 _objects_.
[[interface]]
(((complexity)))(((encapsulation)))(((method)))(((interface)))An
object is a hard shell that hides the gooey complexity inside it
and instead offers us a few knobs and connectors (such as ((method))s)
that present an _interface_ through which the object is to be used.
The idea is that the interface is relatively simple and all the
complex things going on _inside_ the object can be ignored when
working with it.
image::img/object.jpg[alt="A simple interface can hide a lot of complexity.",width="6cm"]
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, ++drawCircle++—and those are the only things you
need to know in order to use such an object.
(((object-oriented programming)))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
_right_ way to program—and that anything that did not involve objects
was outdated nonsense.
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.
I prefer to look at the issue from a practical, rather than
ideological, angle. There are several useful concepts, most
importantly that of _((encapsulation))_ (distinguishing between
internal complexity and external interface), that the object-oriented
culture has popularized. These are worth studying.
This chapter describes JavaScript's rather eccentric take on objects
and the way they relate to some classical object-oriented techniques.
[[obj_methods]]
== Methods ==
(((rabbit example)))(((method)))(((property)))Methods are simply
properties that hold function values. This is a simple method:
[source,javascript]
----
var rabbit = {};
rabbit.speak = function(line) {
console.log("The rabbit says '" + line + "'");
};
rabbit.speak("I'm alive.");
// → The rabbit says 'I'm alive.'
----
(((this)))(((method call)))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
++object.method()++—the special variable `this` in its body will point
to the object that it was called on.
// test: join
// include_code top_lines:6
[source,javascript]
----
function speak(line) {
console.log("The " + this.type + " rabbit says '" +
line + "'");
}
var whiteRabbit = {type: "white", speak: speak};
var fatRabbit = {type: "fat", speak: speak};
whiteRabbit.speak("Oh my ears and whiskers, " +
"how late it's getting!");
// → The white rabbit says 'Oh my ears and whiskers, how
// late it's getting!'
fatRabbit.speak("I could sure use a carrot right now.");
// → The fat rabbit says 'I could sure use a carrot
// right now.'
----
(((apply method)))(((bind method)))(((this)))(((rabbit example)))The
code uses the `this` keyword to output the type of rabbit that is
speaking. Recall that the `apply` and `bind` 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 `this`.
[[call_method]]
(((call method)))There is a method similar to `apply`, called `call`.
It also calls the function it is a method of but takes its arguments
normally, rather than as an array. Like `apply` and `bind`, `call` can
be passed a specific `this` value.
[source,javascript]
----
speak.apply(fatRabbit, ["Burp!"]);
// → The fat rabbit says 'Burp!'
speak.call({type: "old"}, "Oh my.");
// → The old rabbit says 'Oh my.'
----
[[prototypes]]
== Prototypes ==
(((toString method)))Watch closely.
[source,javascript]
----
var empty = {};
console.log(empty.toString);
// → function toString(){…}
console.log(empty.toString());
// → [object Object]
----
(((magic)))I just pulled a property out of an empty object. Magic!
(((property)))(((object)))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
_prototype_. 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.
(((Object prototype)))So who is the ((prototype)) of that empty
object? It is the great ancestral prototype, the entity behind almost
all objects, `Object.prototype`.
[source,javascript]
----
console.log(Object.getPrototypeOf({}) ==
Object.prototype);
// → true
console.log(Object.getPrototypeOf(Object.prototype));
// → null
----
(((getPrototypeOf function)))As you might expect, the
`Object.getPrototypeOf` function returns the prototype of an object.
(((toString method)))The prototype relations of JavaScript objects
form a ((tree))-shaped structure, and at the root of this structure
sits `Object.prototype`. It provides a few ((method))s that show up in
all objects, such as `toString`, which converts an object to a string
representation.
(((inheritance)))(((Function prototype)))(((Array
prototype)))(((Object prototype)))Many objects don't directly have
`Object.prototype` as their ((prototype)), but instead have another
object, which provides its own default properties. Functions derive
from `Function.prototype`, and arrays derive from `Array.prototype`.
[source,javascript]
----
console.log(Object.getPrototypeOf(isNaN) ==
Function.prototype);
// → true
console.log(Object.getPrototypeOf([]) ==
Array.prototype);
// → true
----
(((Object prototype)))Such a prototype object will itself have a
prototype, often `Object.prototype`, so that it still indirectly
provides methods like `toString`.
(((getPrototypeOf function)))(((rabbit example)))(((Object.create
function)))The `Object.getPrototypeOf` function obviously returns the
prototype of an object. You can use `Object.create` to create an
object with a specific ((prototype)).
[source,javascript]
----
var protoRabbit = {
speak: function(line) {
console.log("The " + this.type + " rabbit says '" +
line + "'");
}
};
var killerRabbit = Object.create(protoRabbit);
killerRabbit.type = "killer";
killerRabbit.speak("SKREEEE!");
// → The killer rabbit says 'SKREEEE!'
----
(((shared property)))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.
[[constructors]]
== Constructors ==
(((new operator)))(((this)))(((return keyword)))(((object,creation)))A more convenient way to create objects that derive
from some shared prototype is to use a _((constructor))_. In
JavaScript, calling a function with the `new` keyword in front of it
causes it to be treated as a constructor. The constructor will have
its `this` variable bound to a fresh object, and unless it explicitly
returns another object value, this new object will be returned from
the call.
An object created with `new` is said to be an _((instance))_ of its
constructor.
(((rabbit example)))(((capitalization)))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.
// include_code top_lines:6
[source,javascript]
----
function Rabbit(type) {
this.type = type;
}
var killerRabbit = new Rabbit("killer");
var blackRabbit = new Rabbit("black");
console.log(blackRabbit.type);
// → black
----
(((prototype property)))(((constructor)))Constructors (in fact, all
functions) automatically get a property named `prototype`, which by
default holds a plain, empty object that derives from
`Object.prototype`. Every instance created with this constructor will
have this object as its ((prototype)). So to add a `speak` method to
rabbits created with the `Rabbit` constructor, we can simply do this:
// include_code top_lines:4
[source,javascript]
----
Rabbit.prototype.speak = function(line) {
console.log("The " + this.type + " rabbit says '" +
line + "'");
};
blackRabbit.speak("Doom...");
// → The black rabbit says 'Doom...'
----
(((prototype property)))(((getPrototypeOf function)))It is important
to note the distinction between the way a prototype is associated with
a constructor (through its `prototype` property) and the way objects
_have_ a prototype (which can be retrieved with
`Object.getPrototypeOf`). The actual prototype of a constructor is
`Function.prototype` since constructors are functions. Its
`prototype` _property_ will be the prototype of instances created
through it but is not its _own_ prototype.
== Overriding derived properties ==
(((shared property)))(((overriding)))When you add a ((property)) to an
object, whether it is present in the prototype or not, the property is
added to the object _itself_, which will henceforth have it as its own
property. If there _is_ a property by the same name in the prototype,
this property will no longer affect the object. The prototype itself
is not changed.
[source,javascript]
----
Rabbit.prototype.teeth = "small";
console.log(killerRabbit.teeth);
// → small
killerRabbit.teeth = "long, sharp, and bloody";
console.log(killerRabbit.teeth);
// → long, sharp, and bloody
console.log(blackRabbit.teeth);
// → small
console.log(Rabbit.prototype.teeth);
// → small
----
(((prototype,diagram)))The following diagram sketches the situation
after this code has run. The `Rabbit` and `Object` ((prototype))s lie
behind `killerRabbit` as a kind of backdrop, where properties that are
not found in the object itself can be looked up.
image::img/rabbits.svg[alt="Rabbit object prototype schema",width="8cm"]
(((shared property)))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.
(((toString method)))(((Array prototype)))(((Function prototype)))It
is also used to give the standard function and array prototypes a
different `toString` method than the basic object prototype.
[source,javascript]
----
console.log(Array.prototype.toString ==
Object.prototype.toString);
// → false
console.log([1, 2].toString());
// → 1,2
----
(((toString method)))(((join method)))(((call method)))Calling
`toString` on an array gives a result similar to calling `.join(",")`
on it—it puts commas between the values in the array. Directly calling
`Object.prototype.toString` 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.
[source,javascript]
----
console.log(Object.prototype.toString.call([1, 2]));
// → [object Array]
----
== Prototype interference ==
(((prototype,interference)))(((rabbit example)))(((mutability)))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.
[source,javascript]
----
Rabbit.prototype.dance = function() {
console.log("The " + this.type + " rabbit dances a jig.");
};
killerRabbit.dance();
// → The killer rabbit dances a jig.
----
(((map)))(((object,as map)))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 link:04_data.html#object_map[Chapter 4]:
// include_code
[source,javascript]
----
var map = {};
function storePhi(event, phi) {
map[event] = phi;
}
storePhi("pizza", 0.069);
storePhi("touched tree", -0.081);
----
(((for/in loop)))(((in operator)))We can iterate over all phi values
in the object using a `for`/`in` loop and test whether a name is in
there using the regular `in` operator. But unfortunately, the object's
prototype gets in the way.
[source,javascript]
----
Object.prototype.nonsense = "hi";
for (var name in map)
console.log(name);
// → pizza
// → touched tree
// → nonsense
console.log("nonsense" in map);
// → true
console.log("toString" in map);
// → true
// Delete the problematic property again
delete Object.prototype.nonsense;
----
(((prototype,pollution)))(((toString method)))That's all wrong. There
is no event called “nonsense” in our data set. And there _definitely_
is no event called “toString”.
(((enumerability)))(((for/in loop)))(((property)))Oddly, `toString`
did not show up in the `for`/`in` loop, but the `in` operator did
return true for it. This is because JavaScript distinguishes between
_enumerable_ and _nonenumerable_ properties.
(((Object prototype)))All properties that we create by simply
assigning to them are enumerable. The standard properties in
`Object.prototype` are all nonenumerable, which is why they do not
show up in such a `for`/`in` loop.
(((defineProperty function)))It is possible to define our own
nonenumerable properties by using the `Object.defineProperty`
function, which allows us to control the type of property we are
creating.
[source,javascript]
----
Object.defineProperty(Object.prototype, "hiddenNonsense",
{enumerable: false, value: "hi"});
for (var name in map)
console.log(name);
// → pizza
// → touched tree
console.log(map.hiddenNonsense);
// → hi
----
(((in operator)))(((map)))(((object,as map)))(((hasOwnProperty
method)))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 `in`
operator claiming that the `Object.prototype` properties exist in our
object. For that, we can use the object's `hasOwnProperty` method.
[source,javascript]
----
console.log(map.hasOwnProperty("toString"));
// → false
----
(((property,own)))This method tells us whether the object _itself_ has
the property, without looking at its prototypes. This is often a more
useful piece of information than what the `in` operator gives us.
(((prototype,pollution)))(((for/in loop)))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
`for`/`in` loops like this:
[source,javascript]
----
for (var name in map) {
if (map.hasOwnProperty(name)) {
// ... this is an own property
}
}
----
== Prototype-less objects ==
(((map)))(((object,as map)))(((hasOwnProperty method)))But the
rabbit hole doesn't end there. What if someone registered the name
`hasOwnProperty` in our `map` object and set it to the value 42? Now
the call to `map.hasOwnProperty` will try to call the local property,
which holds a number, not a function.
(((Object.create function)))(((prototype,avoidance)))In such a case,
prototypes just get in the way, and we would actually prefer to have
objects without prototypes. We saw the `Object.create` function, which
allows us to create an object with a specific prototype. You are
allowed to pass `null` as the prototype to create a fresh object with
no prototype. For objects like `map`, where the properties could be
anything, this is exactly what we want.
[source,javascript]
----
var map = Object.create(null);
map["pizza"] = 0.069;
console.log("toString" in map);
// → false
console.log("pizza" in map);
// → true
----
(((in operator)))(((for/in loop)))(((Object prototype)))Much
better! We no longer need the `hasOwnProperty` kludge because all the
properties the object has are its own properties. Now we can safely
use `for`/`in` loops, no matter what people have been doing to
`Object.prototype`.
== Polymorphism ==
(((toString method)))(((String
function)))(((polymorphism)))(((overriding)))When you call the
`String` function, which converts a value to a string, on an object,
it will call the `toString` 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 `toString` so they can
create a string that contains more useful information than
`"[object Object]"`.
(((object-oriented programming)))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 `toString`
method—any kind of object that happens to support this interface can
be plugged into the code, and it will just work.
This technique is called __polymorphism__—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.
[[tables]]
== Laying out a table ==
(((MOUNTAINS data set)))(((table example)))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:
[source,text/plain]
----
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
----
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.
[[table_interface]]
(((table example)))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.
This is the interface:
* `minHeight()` returns a number indicating the minimum height this
cell requires (in lines).
* `minWidth()` returns a number indicating this cell's minimum width (in
characters).
* `draw(width, height)` returns an array of length
`height`, which contains a series of strings that are each `width` characters wide.
This represents the content of the cell.
(((function,higher-order)))I'm going to make heavy use of higher-order
array methods in this example since it lends itself well to that
approach.
(((rowHeights function)))(((colWidths function)))(((maximum)))(((map
method)))(((reduce method)))The first part of the program computes
arrays of minimum column widths and row heights for a grid of cells.
The `rows` variable will hold an array of arrays, with each inner array
representing a row of cells.
// include_code
[source,javascript]
----
function rowHeights(rows) {
return rows.map(function(row) {
return row.reduce(function(max, cell) {
return Math.max(max, cell.minHeight());
}, 0);
});
}
function colWidths(rows) {
return rows[0].map(function(_, i) {
return rows.reduce(function(max, row) {
return Math.max(max, row[i].minWidth());
}, 0);
});
}
----
(((underscore character)))(((programming style)))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.
The `rowHeights` function shouldn't be too hard to follow. It uses
`reduce` to compute the maximum height of an array of cells and wraps
that in `map` in order to do it for all rows in the `rows` array.
(((map method)))(((filter method)))(((forEach
method)))(((array,indexing)))(((reduce method)))Things are slightly
harder for the `colWidths` function because the outer array is an
array of rows, not of columns. I have failed to mention so far that
`map` (as well as `forEach`, `filter`, 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, `colWidths` builds
up an array with one element for every column index. The call to
`reduce` runs over the outer `rows` array for each index and picks
out the width of the widest cell at that index.
(((table example)))(((drawTable function)))Here's the code to draw a
table:
// include_code
[source,javascript]
----
function drawTable(rows) {
var heights = rowHeights(rows);
var widths = colWidths(rows);
function drawLine(blocks, lineNo) {
return blocks.map(function(block) {
return block[lineNo];
}).join(" ");
}
function drawRow(row, rowNum) {
var blocks = row.map(function(cell, colNum) {
return cell.draw(widths[colNum], heights[rowNum]);
});
return blocks[0].map(function(_, lineNo) {
return drawLine(blocks, lineNo);
}).join("\n");
}
return rows.map(drawRow).join("\n");
}
----
(((inner function)))(((nesting,of functions)))The `drawTable` function
uses the internal helper function `drawRow` to draw all rows and then
joins them together with newline characters.
(((table example)))The `drawRow` function itself first converts the
cell objects in the row to _blocks_, 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 `["3776"]`, whereas an underlined cell might
take up two lines and be represented by the array `["name", "----"]`.
(((map method)))(((join method)))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 `map` in `drawRow` 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 `drawRow`’s return value.
The function `drawLine` 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.
[[split]]
(((split method)))(((string,methods)))(((table example)))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 `split`, which
cuts up a string at every occurrence of its argument and returns an
array of the pieces. The `minWidth` method finds the maximum line
width in this array.
// include_code
[source,javascript]
----
function repeat(string, times) {
var result = "";
for (var i = 0; i < times; i++)
result += string;
return result;
}
function TextCell(text) {
this.text = text.split("\n");
}
TextCell.prototype.minWidth = function() {
return this.text.reduce(function(width, line) {
return Math.max(width, line.length);
}, 0);
};
TextCell.prototype.minHeight = function() {
return this.text.length;
};
TextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(line + repeat(" ", width - line.length));
}
return result;
};
----
(((TextCell type)))The code uses a helper function called `repeat`,
which builds a string whose value is the `string` argument repeated
`times` number of times. The `draw` method uses it to add “padding” to
lines so that they all have the required length.
Let's try everything we've written so far by building up a 5 × 5
checkerboard.
[source,javascript]
----
var rows = [];
for (var i = 0; i < 5; i++) {
var row = [];
for (var j = 0; j < 5; j++) {
if ((j + i) % 2 == 0)
row.push(new TextCell("##"));
else
row.push(new TextCell(" "));
}
rows.push(row);
}
console.log(drawTable(rows));
// → ## ## ##
// ## ##
// ## ## ##
// ## ##
// ## ## ##
----
It works! But since all cells have the same size, the table-layout
code doesn't really do anything interesting.
[[mountains]]
(((data set)))(((MOUNTAINS data set)))The source data for the table of
mountains that we are trying to build is available in the `MOUNTAINS`
variable in the ((sandbox)) and also
http://eloquentjavascript.net/code/mountains.js[downloadable] from the
website(!book (http://eloquentjavascript.net/code#6[_eloquentjavascript.net/code#6_])!).
(((table example)))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.
// include_code
[source,javascript]
----
function UnderlinedCell(inner) {
this.inner = inner;
};
UnderlinedCell.prototype.minWidth = function() {
return this.inner.minWidth();
};
UnderlinedCell.prototype.minHeight = function() {
return this.inner.minHeight() + 1;
};
UnderlinedCell.prototype.draw = function(width, height) {
return this.inner.draw(width, height - 1)
.concat([repeat("-", width)]);
};
----
(((UnterlinedCell type)))An underlined cell _contains_ another cell.
It reports its minimum size as being the same as that of its inner
cell (by calling through to that cell's `minWidth` and `minHeight`
methods) but adds one to the height to account for the space taken
up by the underline.
(((concat method)))(((concatenation)))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.
(((dataTable function)))Having an underlining mechanism, we can now
write a function that builds up a grid of cells from our data set.
// test: wrap, trailing
[source,javascript]
----
function dataTable(data) {
var keys = Object.keys(data[0]);
var headers = keys.map(function(name) {
return new UnderlinedCell(new TextCell(name));
});
var body = data.map(function(row) {
return keys.map(function(name) {
return new TextCell(String(row[name]));
});
});
return [headers].concat(body);
}
console.log(drawTable(dataTable(MOUNTAINS)));
// → name height country
// ------------ ------ -------------
// Kilimanjaro 5895 Tanzania
// … etcetera
----
[[keys]]
(((Object.keys function)))(((property)))(((for/in loop)))The standard
`Object.keys` 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 `keys` array so that we are sure that the order of
the cells is the same in every row.
(((right-aligning)))The resulting table resembles the example shown
before, except that it does not right-align the numbers in the
`height` column. We will get to that in a moment.
== Getters and setters ==
(((getter)))(((setter)))(((property)))When specifying an interface, it
is possible to include properties that are not methods. We could have
defined `minHeight` and `minWidth` 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 _constructing_ 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.
(((programming style)))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 `getSomething` and
`setSomething` 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.
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 ((method))s associated with
them.
[source,javascript]
----
var pile = {
elements: ["eggshell", "orange peel", "worm"],
get height() {
return this.elements.length;
},
set height(value) {
console.log("Ignoring attempt to set height to", value);
}
};
console.log(pile.height);
// → 3
pile.height = 100;
// → Ignoring attempt to set height to 100
----
(((defineProperty function)))((({}
(object))))(((getter)))(((setter)))In object literal, the `get` or
`set` 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
`Object.defineProperty` function (which we previously used to create
nonenumerable properties).
[source,javascript]
----
Object.defineProperty(TextCell.prototype, "heightProp", {
get: function() { return this.text.length; }
});
var cell = new TextCell("no\nway");
console.log(cell.heightProp);
// → 2
cell.heightProp = 100;
console.log(cell.heightProp);
// → 2
----
You can use a similar `set` property, in the object passed to
`defineProperty`, to specify a setter method. When a getter but no
setter is defined, writing to the property is simply ignored.
== Inheritance ==
(((inheritance)))(((table example)))(((alignment)))(((TextCell
type)))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 `TextCell`, but rather than padding the
lines on the right side, it pads them on the left side so that they
align to the right.
(((RTextCell type)))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.
// include_code
[source,javascript]
----
function RTextCell(text) {
TextCell.call(this, text);
}
RTextCell.prototype = Object.create(TextCell.prototype);
RTextCell.prototype.draw = function(width, height) {
var result = [];
for (var i = 0; i < height; i++) {
var line = this.text[i] || "";
result.push(repeat(" ", width - line.length) + line);
}
return result;
};
----
(((shared property)))(((overriding)))(((interface)))We reuse the
constructor and the `minHeight` and `minWidth` methods from the
regular `TextCell`. An `RTextCell` is now basically equivalent to a
`TextCell`, except that its `draw` method contains a different
function.
(((call method)))This pattern is called _((inheritance))_. 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 `call` method in order to be able to
give it the new object as its `this` 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.
(((dataTable function)))Now, if we slightly adjust the `dataTable`
function to use ++RTextCell++s for cells whose value is a number, we
get the table we were aiming for.
// start_code bottom_lines: 1
// include_code strip_log
[source,javascript]
----
function dataTable(data) {
var keys = Object.keys(data[0]);
var headers = keys.map(function(name) {
return new UnderlinedCell(new TextCell(name));
});
var body = data.map(function(row) {
return keys.map(function(name) {
var value = row[name];
// This was changed:
if (typeof value == "number")
return new RTextCell(String(value));
else
return new TextCell(String(value));
});
});
return [headers].concat(body);
}
console.log(drawTable(dataTable(MOUNTAINS)));
// → … beautifully aligned table
----
(((object-oriented programming)))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.
(((complexity)))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 _separate_ pieces of
code from each other, reducing the tangledness of the overall program,
((inheritance)) fundamentally ties types together, creating _more_
tangle.
(((code structure)))(((programming style)))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 `UnderlinedCell` builds on another cell
object by simply storing it in a property and forwarding method calls
to it in its own ((method))s.