forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_object.txt
1107 lines (907 loc) · 36.7 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: ["js/code/mountains.js", "js/06_object.js"]
= The Secret Life of Objects =
[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.
____
When a programmer says “object”, that is a loaded term. Objects, in my
profession, are a way of life, the subject of several holy wars, and a
beloved buzzword that still hasn't quite lost its power.
To an outsider, that is probably a little confusing. Let us start with
a brief history of objects as a programming construct.
== History ==
(((object-oriented programming)))(((object)))This story, like most
programming stories, starts with the problem of complexity. One
philosophy is that this complexity can be made manageable by
separating it into small compartments that are isolated from each
other. These compartments ended up with the name “objects”.
(((encapsulation)))(((method)))(((interface)))An object is a hard
shell that encapsulates the gooey complexity inside of it, and instead
offers us a few knobs and connectors (think methods) 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_ of the object can be ignored when working with it.
image::img/object.jpg[alt="A simple interface can hide a lot of complexity"]
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.
These ideas were initially worked out in the 1970s and 80s, and, in
the 90s, 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 feel it is preferable to look at the issue from a practical, rather
than ideological angle. There are several very 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.
== Methods ==
(((rabbit example)))(((method)))(((property)))Methods are simply
properties that hold function values. This is a very 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 variable)))Usually a method needs to do something with the
object it was called on. For example, if there are different rabbits,
the `speak` method must indicate which rabbit is speaking.
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.'
----
The code uses the `this` variable to output the type of rabbit that is
speaking.
(((apply method)))(((bind method)))The first argument to the `apply`
and `bind` methods on functions is in fact used to give a value to
`this`.
There is a method similar to `apply`, called `call`, which also calls
the function, but takes its arguments normally, rather than as an
array. It is used to call a function with 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 ==
(((toString method)))Watch closely.
[source,javascript]
----
var empty = {};
console.log(empty.toString);
// → function toString(){…}
console.log(empty.toString());
// → [object Object]
----
I just pulled a property out of an empty object. Magic!
(((prototype)))(((property)))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 fall-back
source of properties. When a property is requested that an object does
not have, its prototype will be searched for the property, and then
the prototype of the 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, he who is himself prototype-less. His name is
`Object.prototype`.
[source,javascript]
----
console.log(Object.getPrototypeOf({}) ==
Object.prototype);
// → true
console.log(Object.getPrototypeOf(Object.prototype));
// → null
----
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 methods that show up in all objects, such as
`toString`, which converts an object to some string representation.
Many objects don't directly have `Object.prototype` as their
prototype, but instead have another object, which provides additional
default properties. This prototype will itself have a prototype, so
that it still indirectly provides methods like `toString`.
Functions derive from `Function.prototype`, arrays from
`Array.prototype`.
[source,javascript]
----
console.log(Object.getPrototypeOf(isNaN) ==
Function.prototype);
// → true
console.log(Object.getPrototypeOf([]) ==
Array.prototype);
// → true
----
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!'
----
The proto rabbit contains the properties that are shared by all
rabbits. The killer rabbit itself contains the properties that apply
only to that object, in this case its type, and derives the shared
properties from its prototype.
== Constructors ==
(((new operator)))(((this variable)))(((return
keyword)))(((constructor)))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. It will have its `this`
variable bound to a fresh object, and, unless it explicitly returns
something else, this new object will be returned from the call.
Here is a simple constructor for rabbits. It is 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
----
A constructor automatically gets a property `prototype`, which
initially holds a plain object that derives from `Object.prototype`.
New objects created with this constructor will get this object as
their 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...'
----
An object created with `new` is said to be an _((instance))_ of its
constructor.
== Overriding derived properties ==
(((property)))When you add a property to an object, whether it is
present in the prototype or not, that property is added to the object
itself, and the property by the same name in the prototype, if any,
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
----
The following diagram sketches the situation after this code has run.
The `Rabbit` and `Object` prototypes 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"]
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 non-exceptional objects simply take a
standard value from their 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
console.log(Object.prototype.toString.call([1, 2]));
// → [object Array]
----
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, it simply
puts the word “object” and the name of the type between square
brackets.
== Prototype interference ==
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.
----
That's very convenient. But there are situations where it causes
problems. In the previous chapter, 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 a similar
example from Chapter 4:
// include_code
[source,javascript]
----
var ages = {};
function storeAge(name, age) {
ages[name] = age;
}
storeAge("Larry", 58);
storeAge("Simon", 55);
----
(((for/in loop)))(((in operator)))We can iterate over all persons 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 ages)
console.log(name);
// → Larry
// → Simon
// → nonsense
console.log("nonsense" in ages);
// → true
console.log("toString" in ages);
// → true
delete Object.prototype.nonsense;
----
That's all wrong. There is no person called “nonsense” in our data
set. And there _definitely_ is no person called “toString”.
(((enumerability)))Oddly, `toString` did not show up in the `for`/`in`
loop, but the `in` operator did return true for it. JavaScript
distinguishes between _enumerable_ and _non-enumerable_ properties.
All properties that we create by simply assigning to them are
enumerable. The standard properties in `Object.prototype` are all
non-enumerable, which is why they do not show up in such a `for`/`in`
loop.
(((defineProperty function)))It is possible to define our own
non-enumerable properties by using the `Object.defineProperty`
function, which allows us more control of the type of property we are
creating.
[source,javascript]
----
Object.defineProperty(Object.prototype, "hiddenNonsense",
{enumerable: false, value: "hi"});
for (var name in ages)
console.log(name);
// → Larry
// → Simon
console.log(ages.hiddenNonsense);
// → hi
----
(((hasOwnProperty method)))So now the property is there, but it won't
show up in a loop. That is good. But we still have the problem with
the regular `in` operator claiming that the `Object.prototype`
properties exists in our object. For that, we can use the object's
`hasOwnProperty` operator.
[source,javascript]
----
console.log(ages.hasOwnProperty("toString"));
// → false
----
This method tells us whether the object has the property _itself_,
without looking at its prototypes. This is often a more useful piece
of information than what the `in` operator gives us.
When you are worried that someone (some other code you loaded into
your program) might have messed with the base object prototype, it is
recommended to write your `for`/`in` loops like this:
[source,javascript]
----
for (var name in ages) {
if (ages.hasOwnProperty(name)) {
// ... this is a real property
}
}
----
== Prototype-less objects ==
But the rabbit hole doesn't end there. What if someone registered the
name `hasOwnProperty` in our `ages` object? Now the call to
`ages.hasOwnProperty` will try to call the local property, which will
hold a number, not a function.
Often, prototypes just get in the way, and we actually want nothing to
do with them. 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 `ages`, where the properties could be anything, this
is exactly what we want.
[source,javascript]
----
var ages = Object.create(null);
ages.Brendan = 52;
console.log("toString" in ages);
// → false
console.log("Brendan" in ages);
// → true
----
Much better! Now we do not need the `hasOwnProperty` kludge—because
all the properties the object has are its own properties—and we can
safely use `for`/`in` loops, no matter what people have been doing to
`Object.prototype`.
== Polymorphism ==
(((toString method)))(((String function)))(((polymorphism)))When you
call the `String` function on an object, it will call the `toString`
method on that object to try and create a meaningful string to return.
I mentioned that some of the standard prototypes define their own
version of `toString`, in order to be able to create a string that
contains more useful information than `"[object Object]"`.
This is a simple instance of a very 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 shape, as long as they expose the interface it expects.
== Laying out a table ==
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 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
Mount McKinley 6168 United States
Popocatepetl 5465 Mexico
----
The way our table-building system will work is that the builder
function lets the cells tell it how wide and high they want to be, and
then, once it has determined the width of the columns and the height
of the rows, asks them to draw themselves at the correct size
and assembles the result into a single string.
The interface through which the algorithm talks to the cells consists
of these methods:
* `minHeight()` returns a number indicating the minimum height this
cell requires (in lines).
* `minWidth()` returns a number indicating its minimum width (in
characters).
* `draw(width, height)` returns an array of strings with length
`height`, each of them `width` characters wide. This represents the
content of the cell.
I'm going to make heavy use of higher-order array methods in this
example, since it lends itself well to that approach.
The first part of the program computes arrays of minimum column widths
and row heights from a collection 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);
});
}
----
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)))(((filter 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)
pass a second argument to the function they are given, namely the
index of the current element. By mapping over the elements of the
first row, and only using its second argument, `colWidths` builds up
an array with one element for every column index. The call to `reduce`
runs over the outer `rows` array again, and picks out the cell at the
given index from each row, maximizing their widths.
Using an underscore (`_`) as an argument name is a way to indicate (to
human readers) that this argument is not going to be used.
Drawing a table now looks like this:
// 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");
}
----
The `drawTable` function uses internal helper functions `drawRow` and
`drawLine`. The first produces a string for a single row of the table,
and the second is used to render a single line, given an array of
blocks (arrays of strings) and a line number. The outer function, at
its very end, simply draws all rows and joins them together with
newline characters.
The `drawRow` function itself does something similar. It first draws
each cell using the correct dimensions, and then maps over all the
lines in the first cell in order to call `drawLine` for each line the
row has, and joins the result, again, with newline characters.
Let us write a constructor for cells that contain text. The
constructor splits a string into an array of lines, and 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;
};
----
The `repeat` function helps build up strings that repeat a single
character a given number of times. The `draw` method uses it to add
“padding” to lines, so that they all have the required length.
Let's try it out by building up a 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, it doesn't really do
anything interesting.
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
list of data sets on the website!!tex (`eloquentjavascript.net/code`)!!.
We will want to emphasize 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)]);
};
----
An underlined cell _contains_ another cell. It report 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, which is the space taken up by the underline.
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.
// 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
----
Having an underlining mechanism, we can now write a function that
builds up a grid of cells from our data set. 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.
== 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, and
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.
This has led some people to adopt a principle of never including
non-method properties in interfaces. For things that behave as a
simple value property, which can be both read and written, they'd use
`getSomething` and `setSomething` methods which read and write the
property.
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.
[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)))In object expressions, putting `get` or
`set` in front of a property name 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 also used to create
non-enumerable properties).
[source,javascript]
----
Object.defineProperty(TextCell.prototype, "heightProp", {
get: function() { return this.text.length; }
});
console.log((new TextCell("no\nway")).heightProp);
// → 2
----
You can use a similar `set` property to specify a setter method. When
a getter but no setter is defined, writing to the property is simply
ignored.
== Inheritance ==
(((inheritance)))If you have paid close attention, you might have
noticed that 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, pads them on the left side, so
that they align to the right.
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;
};
----
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.
This pattern is called _inheritance_. It allows us to build slightly
different data types from existing datatypes 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.
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:
// 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];
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
----
Inheritance is a fundamental part of the object-oriented tradition,
alongside encapsulation and polymorphism. The latter two are now
generally regarded as wonderful ideas, whereas inheritance is somewhat
controversial.
(((polymorphism)))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 the types that inherit
from each other together, creating _more_ tangle.
(((composition)))You can have polymorphism without inheritance, as we
saw. I am not going to tell you to avoid inheritance—I use it
regularly in my own programs. But 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. The way `UnderlinedCell` builds on
another cell object, by simply storing it in a property and forwarding
method calls to it in its own methods, is an alternative way to extend
types, and is usually preferable.
== The instanceof operator ==
(((instanceof operator)))(((constructor)))It is occasionally useful to
know whether an object was derived from a specific constructor. For
this, JavaScript provides a binary operator called `instanceof`:
[source,javascript]
----
console.log(new RTextCell("A") instanceof RTextCell);
// → true
console.log(new RTextCell("A") instanceof TextCell);
// → true
console.log(new TextCell("A") instanceof RTextCell);
// → false
console.log([1] instanceof Array);
// → true
----
The operator will also see through inherited types. An `RTextCell` is
an instance of `TextCell`, because `RTextCell.prototype` derives from
`TextCell.prototype`. The operator can be applied to standard
constructors like `Array`. Almost every object is an instance of
`Object`.
== Summary ==
(((prototype)))So objects are more complicated than I initially
pictured them. They have prototypes, which are other objects, and will
act as if they have properties they don't have if the prototype has
that property. Simple objects have `Object.prototype` as their
prototype.
(((constructor)))(((new operator)))(((instanceof
operator)))Constructors, which are functions whose name usually starts
with a capital letter, can be used with the `new` operator to create
new objects. The new object's prototype will be the object found in
the `prototype` 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 `instanceof` operator can, given
an object and a constructor, tell you whether that object is an
instance of that constructor.
(((encapsulation)))One useful thing to do with objects is to specify
an interface for them, and tell everybody that they are only supposed
to talk to your object through that interface (which consists of some
properties). The rest of the details that make up your object are now
_encapsulated_, hidden behind the interface.
(((polymorphism)))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 _polymorphism_.
It is very useful.
(((inheritance)))When implementing multiple types that only differ in
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 very
similar to the old type, but in which you can add and override
properties as you see fit.
== Exercises ==
=== A point type ===
Write a constructor `Point` that represents a point in two-dimensional
space. It takes `x` and `y` parameters (numbers), which it saves to
properties by the same name.
Give the `Point` prototype two methods, `plus` and `minus`, which take
another point as a parameter, and return a new point that has the sum or
difference of the two points’ (the one in `this` and the parameter) x
and y coordinates.
Add a getter property `distance` to the prototype that computes the
distance of a point from the origin (0, 0).
ifdef::html_target[]
// test: no
[source,javascript]
----
// Your code here.
console.log(new Point(1, 2).plus(new Point(2, 3)));
// → Point{x: 3, y: 5}
console.log(new Point(1, 2).minus(new Point(2, 3)));
// → Point{x: -1, y: -1}
console.log(new Point(3, 4).distance);
// → 5
----
endif::html_target[]
!!solution!!
Your solution can follow the pattern of the `Rabbit` constructor from
this chapter quite closely.
(((Pythagoras)))Adding a getter property to the constructor can be
done with the `Object.defineProperty` function. To compute the
distance from (0, 0) to (x, y), we can use Pythagoras’ theorem, which