mirror of
https://github.com/apachecn/eloquent-js-3e-zh.git
synced 2025-05-23 20:02:20 +00:00
1091 lines
70 KiB
Diff
1091 lines
70 KiB
Diff
diff --git a/2ech6.md b/3ech6.md
|
||
index cc81bf0..9f69b59 100644
|
||
--- a/2ech6.md
|
||
+++ b/3ech6.md
|
||
@@ -1,90 +1,96 @@
|
||
# Chapter 6The Secret Life of Objects
|
||
|
||
-> 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.
|
||
+> An abstract data type is realized by writing a special kind of program […] which defines the type in terms of the operations which can be performed on it.
|
||
>
|
||
-> <footer>Joe Armstrong, <cite>interviewed in Coders at Work</cite></footer>
|
||
+> <footer>Barbara Liskov, <cite>Programming with Abstract Data Types</cite></footer>
|
||
|
||
-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.
|
||
+[Chapter 4](04_data.html) introduced JavaScript's objects. In programming culture, we have a thing called _object-oriented programming_, a set of techniques that use objects (and related concepts) as the central principle of program organization.
|
||
|
||
-To an outsider, this is probably a little confusing. Let's start with a brief history of objects as a programming construct.
|
||
+Though no one really agrees on its precise definition, object-oriented programming has shaped the design of many programming languages, including JavaScript. This chapter will describe the way these ideas can be applied in JavaScript.
|
||
|
||
-## History
|
||
+## Encapsulation
|
||
|
||
-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_.
|
||
+The core idea in object-oriented programming is to divide programs into smaller pieces and make each piece responsible for managing its own state.
|
||
|
||
-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 _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.
|
||
+This way, some knowledge about the way a piece of the program works can be kept _local_ to that piece. Someone working on the rest of the program does not have to remember or even be aware of that knowledge. Whenever these local details change, only the code directly around it needs to be updated.
|
||
|
||
-
|
||
+Different pieces of such a program interact with each other through _interfaces_, limited sets of functions or bindings that provide useful functionality at a more abstract level, hiding its precise implementation.
|
||
|
||
-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.
|
||
+Such program pieces are modeled using objects. Their interface consists of a specific set of methods and properties. Properties that are part of the interface are called _public_. The others, which outside code should not be touching, are called _private_.
|
||
|
||
-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.
|
||
+Many languages provide a way to distinguish public and private properties and will prevent outside code from accessing the private ones altogether. JavaScript, once again taking the minimalist approach, does not. Not yet, at least—there is work underway to add this to the language.
|
||
|
||
-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.
|
||
+Even though the language doesn't have this distinction built in, JavaScript programmers _are_ successfully using this idea. Typically, the available interface is described in documentation or comments. It is also common to put an underscore (`_`) character at the start of property names to indicate that those properties are private.
|
||
|
||
-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.
|
||
+Separating interface from implementation is a great idea. It is usually called _encapsulation_.
|
||
|
||
## Methods
|
||
|
||
-Methods are simply properties that hold function values. This is a simple method:
|
||
+Methods are nothing more than properties that hold function values. This is a simple method:
|
||
|
||
```
|
||
-var rabbit = {};
|
||
+let rabbit = {};
|
||
rabbit.speak = function(line) {
|
||
- console.log("The rabbit says '" + line + "'");
|
||
+ console.log(`The rabbit says '${line}'`);
|
||
};
|
||
|
||
rabbit.speak("I'm alive.");
|
||
// → The rabbit says 'I'm alive.'
|
||
```
|
||
|
||
-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.
|
||
+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 binding called `this` in its body automatically points at the object that it was called on.
|
||
|
||
```
|
||
function speak(line) {
|
||
- console.log("The " + this.type + " rabbit says '" +
|
||
- line + "'");
|
||
+ console.log(`The ${this.type} rabbit says '${line}'`);
|
||
}
|
||
-var whiteRabbit = {type: "white", speak: speak};
|
||
-var fatRabbit = {type: "fat", speak: speak};
|
||
+let whiteRabbit = {type: "white", speak};
|
||
+let hungryRabbit = {type: "hungry", 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.'
|
||
+hungryRabbit.speak("I could use a carrot right now.");
|
||
+// → The hungry rabbit says 'I could use a carrot right now.'
|
||
+```
|
||
+
|
||
+You can think of `this` as an extra parameter that is passed in a different way. If you want to pass it explicitly, you can use a function's `call` method, which takes the `this` value as first argument and treats further arguments as normal parameters.
|
||
+
|
||
+```
|
||
+speak.call(hungryRabbit, "Burp!");
|
||
+// → The hungry rabbit says 'Burp!'
|
||
```
|
||
|
||
-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`.
|
||
+Since each function has its own `this` binding, whose value depends on the way it is called, you cannot refer to the `this` of the wrapping scope in a regular function defined with the `function` keyword.
|
||
|
||
-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.
|
||
+Arrow functions are different—they do not bind their own `this`, but can see the `this` binding of the scope around them. Thus, you can do something like the following code, which references `this` from inside a local function:
|
||
|
||
```
|
||
-speak.apply(fatRabbit, ["Burp!"]);
|
||
-// → The fat rabbit says 'Burp!'
|
||
-speak.call({type: "old"}, "Oh my.");
|
||
-// → The old rabbit says 'Oh my.'
|
||
+function normalize() {
|
||
+ console.log(this.coords.map(n => n / this.length));
|
||
+}
|
||
+normalize.call({coords: [0, 2, 3], length: 5});
|
||
+// → [0, 0.4, 0.6]
|
||
```
|
||
|
||
+If I had written the argument to `map` using the `function` keyword, the code wouldn't work.
|
||
+
|
||
## Prototypes
|
||
|
||
Watch closely.
|
||
|
||
```
|
||
-var empty = {};
|
||
+let empty = {};
|
||
console.log(empty.toString);
|
||
// → function toString(){…}
|
||
console.log(empty.toString());
|
||
// → [object Object]
|
||
```
|
||
|
||
-I just pulled a property out of an empty object. Magic!
|
||
+I pulled a property out of an empty object. Magic!
|
||
|
||
-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.
|
||
+Well, not really. I have simply been withholding information about the way JavaScript objects work. In addition to their set of properties, most 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.
|
||
|
||
So who is the prototype of that empty object? It is the great ancestral prototype, the entity behind almost all objects, `Object.prototype`.
|
||
|
||
@@ -96,14 +102,14 @@ console.log(Object.getPrototypeOf(Object.prototype));
|
||
// → null
|
||
```
|
||
|
||
-As you might expect, the `Object.getPrototypeOf` function returns the prototype of an object.
|
||
+As you guess, `Object.<wbr>getPrototypeOf` returns the prototype of an object.
|
||
|
||
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 a string representation.
|
||
|
||
-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`.
|
||
+Many objects don't directly have `Object.prototype` as their prototype, but instead have another object that provides a different set of default properties. Functions derive from `Function.<wbr>prototype`, and arrays derive from `Array.prototype`.
|
||
|
||
```
|
||
-console.log(Object.getPrototypeOf(isNaN) ==
|
||
+console.log(Object.getPrototypeOf(Math.max) ==
|
||
Function.prototype);
|
||
// → true
|
||
console.log(Object.getPrototypeOf([]) ==
|
||
@@ -113,58 +119,103 @@ console.log(Object.getPrototypeOf([]) ==
|
||
|
||
Such a prototype object will itself have a prototype, often `Object.prototype`, so that it still indirectly provides methods like `toString`.
|
||
|
||
-The `Object.getPrototypeOf` function obviously returns the prototype of an object. You can use `Object.create` to create an object with a specific prototype.
|
||
+You can use `Object.create` to create an object with a specific prototype.
|
||
|
||
```
|
||
-var protoRabbit = {
|
||
- speak: function(line) {
|
||
- console.log("The " + this.type + " rabbit says '" +
|
||
- line + "'");
|
||
+let protoRabbit = {
|
||
+ speak(line) {
|
||
+ console.log(`The ${this.type} rabbit says '${line}'`);
|
||
}
|
||
};
|
||
-var killerRabbit = Object.create(protoRabbit);
|
||
+let killerRabbit = Object.create(protoRabbit);
|
||
killerRabbit.type = "killer";
|
||
killerRabbit.speak("SKREEEE!");
|
||
// → The killer rabbit says 'SKREEEE!'
|
||
```
|
||
|
||
+A property like `speak(line)` in an object expression is a shorthand for defining a method. It creates a property called `speak` and gives it a function as its value.
|
||
+
|
||
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
|
||
+## Classes
|
||
|
||
-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.
|
||
+JavaScript's prototype system can be interpreted as a somewhat informal take on an object-oriented concept called _classes_. A class defines the shape of a type of object—what methods and properties it has. Such an object is called an _instance_ of the class.
|
||
|
||
-An object created with `new` is said to be an _instance_ of its constructor.
|
||
+Prototypes are useful for defining properties for which all instances of a class share the same value, such as methods. Properties that differ per instance, such as our rabbits' `type` property, need to be stored directly in the objects themselves.
|
||
|
||
-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.
|
||
+So in order to create an instance of a given class, you have to make an object that derives from the proper prototype, but you _also_ have to make sure it, itself, has the properties that instances of this class are supposed to have. This is what a _constructor_ function does.
|
||
+
|
||
+```
|
||
+function makeRabbit(type) {
|
||
+ let rabbit = Object.create(protoRabbit);
|
||
+ rabbit.type = type;
|
||
+ return rabbit;
|
||
+}
|
||
+```
|
||
+
|
||
+JavaScript provides a way to make defining this type of function easier. If you put the keyword `new` in front of a function call, the function is treated as a constructor. This means that an object with the right prototype is automatically created, bound to `this` in the function, and returned at the end of the function.
|
||
+
|
||
+The prototype object used when constructing objects is found by taking the `prototype` property of the constructor function.
|
||
|
||
```
|
||
function Rabbit(type) {
|
||
this.type = type;
|
||
}
|
||
+Rabbit.prototype.speak = function(line) {
|
||
+ console.log(`The ${this.type} rabbit says '${line}'`);
|
||
+};
|
||
|
||
-var killerRabbit = new Rabbit("killer");
|
||
-var blackRabbit = new Rabbit("black");
|
||
-console.log(blackRabbit.type);
|
||
-// → black
|
||
+let weirdRabbit = new Rabbit("weird");
|
||
```
|
||
|
||
-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:
|
||
+Constructors (all functions, in fact) automatically get a property named `prototype`, which by default holds a plain, empty object that derives from `Object.prototype`. You can overwrite it with a new object if you want. Or you can add properties to the existing object, as the example does.
|
||
+
|
||
+By convention, the names of constructors are capitalized so that they can easily be distinguished from other functions.
|
||
+
|
||
+It is important to understand 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 found with `Object.<wbr>getPrototypeOf`). The actual prototype of a constructor is `Function.<wbr>prototype`, since constructors are functions. Its `prototype` _property_ holds the prototype used for instances created through it.
|
||
|
||
```
|
||
-Rabbit.prototype.speak = function(line) {
|
||
- console.log("The " + this.type + " rabbit says '" +
|
||
- line + "'");
|
||
-};
|
||
-blackRabbit.speak("Doom...");
|
||
-// → The black rabbit says 'Doom...'
|
||
+console.log(Object.getPrototypeOf(Rabbit) ==
|
||
+ Function.prototype);
|
||
+// → true
|
||
+console.log(Object.getPrototypeOf(weirdRabbit) ==
|
||
+ Rabbit.prototype);
|
||
+// → true
|
||
+```
|
||
+
|
||
+## Class notation
|
||
+
|
||
+So JavaScript classes are constructor functions with a prototype property. That is how they work, and until 2015, that was how you had to write them. These days, we have a less awkward notation.
|
||
+
|
||
+```
|
||
+class Rabbit {
|
||
+ constructor(type) {
|
||
+ this.type = type;
|
||
+ }
|
||
+ speak(line) {
|
||
+ console.log(`The ${this.type} rabbit says '${line}'`);
|
||
+ }
|
||
+}
|
||
+
|
||
+let killerRabbit = new Rabbit("killer");
|
||
+let blackRabbit = new Rabbit("black");
|
||
```
|
||
|
||
-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.
|
||
+The `class` keyword starts a class declaration, which allows us to define a constructor and a set of methods all in a single place. Any number of methods may be written inside the declaration's curly braces. The one named `constructor` is treated specially. It provides the actual constructor function, which will be bound to the name `Rabbit`. The others are packaged into that constructor's prototype. Thus, the class declaration above is equivalent to the constructor definition from the previous section. It just looks nicer.
|
||
+
|
||
+Class declarations currently only allow _methods_—properties that hold functions—to be added to the prototype. This can be somewhat inconvenient when you want to save a non-function value in there. The next version of the language will probably improve this. For now, you can create such properties by directly manipulating the prototype after you've defined the class.
|
||
+
|
||
+Like `function`, `class` can be used both in statement and in expression positions. When used as an expression, it doesn't define a binding, but just produces the constructor as a value. You are allowed to omit the class name in a class expression.
|
||
+
|
||
+```
|
||
+let object = new class { getWord() { return "hello"; } };
|
||
+console.log(object.getWord());
|
||
+// → hello
|
||
+```
|
||
|
||
## Overriding derived properties
|
||
|
||
-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.
|
||
+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_. If there was already a property with the same name in the prototype, this property will no longer affect the object, as it is now hidden behind the object's own property.
|
||
|
||
```
|
||
Rabbit.prototype.teeth = "small";
|
||
@@ -181,11 +232,11 @@ console.log(Rabbit.prototype.teeth);
|
||
|
||
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.
|
||
|
||
-
|
||
+<figure></figure>
|
||
|
||
-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.
|
||
+Overriding properties that exist in a prototype can be 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 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.
|
||
+Overriding is also used to give the standard function and array prototypes a different `toString` method than the basic object prototype.
|
||
|
||
```
|
||
console.log(Array.prototype.toString ==
|
||
@@ -195,512 +246,456 @@ console.log([1, 2].toString());
|
||
// → 1,2
|
||
```
|
||
|
||
-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.
|
||
+Calling `toString` on an array gives a result similar to calling `.<wbr>join(",")` on it—it puts commas between the values in the array. Directly calling `Object.<wbr>prototype.<wbr>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.
|
||
|
||
```
|
||
console.log(Object.prototype.toString.call([1, 2]));
|
||
// → [object Array]
|
||
```
|
||
|
||
-## Prototype interference
|
||
+## Maps
|
||
|
||
-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.
|
||
+We saw the word _map_ used in the [previous chapter](05_higher_order.html#map) for an operation that transforms a data structure by applying a function its elements. Confusing as it is, in programming the same word is also used for a related but rather different thing.
|
||
+
|
||
+A _map_ (noun) is a data structure that associates values (the keys) with other values. For example, you might want to map names to ages. It is possible to use objects for this.
|
||
|
||
```
|
||
-Rabbit.prototype.dance = function() {
|
||
- console.log("The " + this.type + " rabbit dances a jig.");
|
||
+let ages = {
|
||
+ Boris: 39,
|
||
+ Liang: 22,
|
||
+ Júlia: 62
|
||
};
|
||
-killerRabbit.dance();
|
||
-// → The killer rabbit dances a jig.
|
||
-```
|
||
-
|
||
-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 [Chapter 4](04_data.html#object_map):
|
||
|
||
+console.log(`Júlia is ${ages["Júlia"]}`);
|
||
+// → Júlia is 62
|
||
+console.log("Is Jack's age known?", "Jack" in ages);
|
||
+// → Is Jack's age known? false
|
||
+console.log("Is toString's age known?", "toString" in ages);
|
||
+// → Is toString's age known? true
|
||
```
|
||
-var map = {};
|
||
-function storePhi(event, phi) {
|
||
- map[event] = phi;
|
||
-}
|
||
|
||
-storePhi("pizza", 0.069);
|
||
-storePhi("touched tree", -0.081);
|
||
-```
|
||
+Here, the object's property names are the people's names, and the property values their ages. But we certainly didn't list anybody named toString in our map. Yet, because plain objects derive from `Object.prototype`, it looks like the property is there.
|
||
|
||
-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.
|
||
+As such, using plain objects as maps is dangerous. There are several possible ways to avoid this problem. First, it is possible to create objects with _no_ prototype. If you pass `null` to `Object.create`, the resulting object will not derive from `Object.prototype` and can safely be used as a map.
|
||
|
||
```
|
||
-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;
|
||
+console.log("toString" in Object.create(null));
|
||
+// → false
|
||
```
|
||
|
||
-That's all wrong. There is no event called “nonsense” in our data set. And there _definitely_ is no event called “toString”.
|
||
-
|
||
-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 property names must be strings. If you need a map whose keys can't easily be converted to strings—such as objects—you cannot use an object as your map.
|
||
|
||
-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.
|
||
+Fortunately, JavaScript comes with a class called `Map` that is written for this exact purpose. It stores a mapping and allows any type of keys.
|
||
|
||
-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.
|
||
-
|
||
-```
|
||
-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
|
||
```
|
||
+let ages = new Map();
|
||
+ages.set("Boris", 39);
|
||
+ages.set("Liang", 22);
|
||
+ages.set("Júlia", 62);
|
||
|
||
-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.
|
||
-
|
||
-```
|
||
-console.log(map.hasOwnProperty("toString"));
|
||
+console.log(`Júlia is ${ages.get("Júlia")}`);
|
||
+// → Júlia is 62
|
||
+console.log("Is Jack's age known?", ages.has("Jack"));
|
||
+// → Is Jack's age known? false
|
||
+console.log(ages.has("toString"));
|
||
// → false
|
||
```
|
||
|
||
-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.
|
||
+The methods `set`, `get`, and `has` are part of the interface of the `Map` object. Writing a data structure that can quickly update and search a large set of values isn't easy, but we don't have to worry about that. Someone else did it for us, and we can go through this simple interface to use their work.
|
||
|
||
-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:
|
||
+If you do have a plain object that you need to treat as a map for some reason, it is useful to know that `Object.keys` only returns an object's _own_ keys, not those in the prototype. As an alternative to the `in` operator, you can use the `hasOwnProperty` method, which ignores the object's prototype.
|
||
|
||
```
|
||
-for (var name in map) {
|
||
- if (map.hasOwnProperty(name)) {
|
||
- // ... this is an own property
|
||
- }
|
||
-}
|
||
+console.log({x: 1}.hasOwnProperty("x"));
|
||
+// → true
|
||
+console.log({x: 1}.hasOwnProperty("toString"));
|
||
+// → false
|
||
```
|
||
|
||
-## Prototype-less objects
|
||
-
|
||
-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.
|
||
+## Polymorphism
|
||
|
||
-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.
|
||
+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 from it. 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]"`. You can also do that yourself.
|
||
|
||
```
|
||
-var map = Object.create(null);
|
||
-map["pizza"] = 0.069;
|
||
-console.log("toString" in map);
|
||
-// → false
|
||
-console.log("pizza" in map);
|
||
-// → true
|
||
+Rabbit.prototype.toString = function() {
|
||
+ return `a ${this.type} rabbit`;
|
||
+};
|
||
+
|
||
+console.log(String(blackRabbit));
|
||
+// → a black rabbit
|
||
```
|
||
|
||
-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`.
|
||
+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.
|
||
|
||
-## Polymorphism
|
||
+This technique is called _polymorphism_. Polymorphic code can work with values of different shapes, as long as they support the interface it expects.
|
||
|
||
-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]"`.
|
||
+I mentioned in [Chapter 4](04_data.html#for_of_loop) that a `for`/`of` loop can loop over several kinds of data structures. This is another case of polymorphism—such loops expect the data structure to expose a specific interface, which arrays and strings do. And you can also add this interface to your own objects! But before we can do that, we need to know what symbols are.
|
||
|
||
-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.
|
||
+## Symbols
|
||
|
||
-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.
|
||
+It is possible for multiple interfaces to use the same property name for different things. For example, I could define an interface in which the `toString` method is supposed to convert the object into a piece of yarn. It would not be possible for an object to conform to both that interface and the standard use of `toString`.
|
||
|
||
-## Laying out a table
|
||
+That would be a bad idea, and this problem isn't that common. Most JavaScript programmers simply don't think about it. But the language designers, whose _job_ it is to think about this stuff, have provided us with a solution anyway.
|
||
|
||
-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:
|
||
+When I claimed that property names are strings, that wasn't entirely accurate. They usually are, but they can also be _symbols_. Symbols are values created with the `Symbol` function. Unlike strings, newly created symbols are unique—you cannot create the same symbol twice.
|
||
|
||
```
|
||
-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
|
||
+let sym = Symbol("name");
|
||
+console.log(sym == Symbol("name"));
|
||
+// → false
|
||
+Rabbit.prototype[sym] = 55;
|
||
+console.log(blackRabbit[sym]);
|
||
+// → 55
|
||
```
|
||
|
||
-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.
|
||
+The string you pass to `Symbol` is included when you convert it to a string, and can make it easier to recognize a symbol when, for example, showing it in the console. But it has no meaning beyond that—multiple symbols may have the same name.
|
||
|
||
-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.
|
||
+Being both unique and useable as property names makes symbols suitable for defining interfaces that can peacefully live alongside other properties, no matter what their names are.
|
||
|
||
-This is the interface:
|
||
-
|
||
-* `minHeight()` returns a number indicating the minimum height this cell requires (in lines).
|
||
+```
|
||
+const toStringSymbol = Symbol("toString");
|
||
+Array.prototype[toStringSymbol] = function() {
|
||
+ return `${this.length} cm of blue yarn`;
|
||
+};
|
||
|
||
-* `minWidth()` returns a number indicating this cell's minimum width (in characters).
|
||
+console.log([1, 2].toString());
|
||
+// → 1,2
|
||
+console.log([1, 2][toStringSymbol]());
|
||
+// → 2 cm of blue yarn
|
||
+```
|
||
|
||
-* `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.
|
||
+It is possible to include symbol properties in object expressions and classes by using square brackets around the property name. That causes the property name to be evaluated, much like the square bracket property access notation, which allows us to refer to a binding that holds the symbol.
|
||
|
||
-I'm going to make heavy use of higher-order array methods in this example since it lends itself well to that approach.
|
||
+```
|
||
+let stringObject = {
|
||
+ [toStringSymbol]() { return "a jute rope"; }
|
||
+};
|
||
+console.log(stringObject[toStringSymbol]());
|
||
+// → a jute rope
|
||
+```
|
||
|
||
-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.
|
||
+## The iterator interface
|
||
|
||
-```
|
||
-function rowHeights(rows) {
|
||
- return rows.map(function(row) {
|
||
- return row.reduce(function(max, cell) {
|
||
- return Math.max(max, cell.minHeight());
|
||
- }, 0);
|
||
- });
|
||
-}
|
||
+The object given to a `for`/`of` loop is expected to be _iterable_. This means that it has a method named with the `Symbol.iterator` symbol (a symbol value defined by the language, stored as a property of the `Symbol` function).
|
||
|
||
-function colWidths(rows) {
|
||
- return rows[0].map(function(_, i) {
|
||
- return rows.reduce(function(max, row) {
|
||
- return Math.max(max, row[i].minWidth());
|
||
- }, 0);
|
||
- });
|
||
-}
|
||
-```
|
||
+When called, that method should return an object that provides a second interface, _iterator_. This is the actual thing that iterates. It has a `next` method that returns the next result. That result should be an object with a `value` property, providing the next value, if there is one, and a `done` property which should be true when there are no more results and false otherwise.
|
||
|
||
-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.
|
||
+Note that the `next`, `value`, and `done` property names are plain strings, not symbols. Only `Symbol.iterator`, which is likely to be added to a _lot_ of different objects, is an actual symbol.
|
||
|
||
-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.
|
||
+We can directly use this interface ourselves.
|
||
|
||
-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.
|
||
+```
|
||
+let okIterator = "OK"[Symbol.iterator]();
|
||
+console.log(okIterator.next());
|
||
+// → {value: "O", done: false}
|
||
+console.log(okIterator.next());
|
||
+// → {value: "K", done: false}
|
||
+console.log(okIterator.next());
|
||
+// → {value: undefined, done: true}
|
||
+```
|
||
|
||
-Here's the code to draw a table:
|
||
+Let's implement an iterable data structure. We'll build a _matrix_ class, acting as a two-dimensional array.
|
||
|
||
```
|
||
-function drawTable(rows) {
|
||
- var heights = rowHeights(rows);
|
||
- var widths = colWidths(rows);
|
||
+class Matrix {
|
||
+ constructor(width, height, element = (x, y) => undefined) {
|
||
+ this.width = width;
|
||
+ this.height = height;
|
||
+ this.content = [];
|
||
|
||
- function drawLine(blocks, lineNo) {
|
||
- return blocks.map(function(block) {
|
||
- return block[lineNo];
|
||
- }).join(" ");
|
||
+ for (let y = 0; y < height; y++) {
|
||
+ for (let x = 0; x < width; x++) {
|
||
+ this.content[y * width + x] = element(x, y);
|
||
+ }
|
||
+ }
|
||
}
|
||
|
||
- 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");
|
||
+ get(x, y) {
|
||
+ return this.content[y * this.width + x];
|
||
+ }
|
||
+ set(x, y, value) {
|
||
+ this.content[y * this.width + x] = value;
|
||
}
|
||
-
|
||
- return rows.map(drawRow).join("\n");
|
||
}
|
||
```
|
||
|
||
-The `drawTable` function uses the internal helper function `drawRow` to draw all rows and then joins them together with newline characters.
|
||
-
|
||
-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", "----"]`.
|
||
+The class stores its content in a single array of _width_ × _height_ elements. The elements are stored row-by-row, so, for example, the third element in the fifth row is (using zero-based indexing) stored at position 4 × _width_ + 2.
|
||
|
||
-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 constructor function takes a width, height, and an optional content function that will be used to fill in the initial values. There are `get` and `set` methods to retrieve and update elements in the matrix.
|
||
|
||
-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.
|
||
-
|
||
-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.
|
||
+When looping over a matrix, you are usually interested in the position of the elements as well as the elements themselves, so we'll have our iterator produce objects with `x`, `y`, and `value` properties.
|
||
|
||
```
|
||
-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));
|
||
+class MatrixIterator {
|
||
+ constructor(matrix) {
|
||
+ this.x = 0;
|
||
+ this.y = 0;
|
||
+ this.matrix = matrix;
|
||
}
|
||
- return result;
|
||
-};
|
||
-```
|
||
-
|
||
-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.
|
||
-
|
||
-```
|
||
-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);
|
||
+ next() {
|
||
+ if (this.y == this.matrix.height) return {done: true};
|
||
+
|
||
+ let value = {x: this.x,
|
||
+ y: this.y,
|
||
+ value: this.matrix.get(this.x, this.y)};
|
||
+ this.x++;
|
||
+ if (this.x == this.matrix.width) {
|
||
+ this.x = 0;
|
||
+ this.y++;
|
||
+ }
|
||
+ return {value, done: false};
|
||
+ }
|
||
}
|
||
-console.log(drawTable(rows));
|
||
-// → ## ## ##
|
||
-// ## ##
|
||
-// ## ## ##
|
||
-// ## ##
|
||
-// ## ## ##
|
||
```
|
||
|
||
-It works! But since all cells have the same size, the table-layout code doesn't really do anything interesting.
|
||
+The class tracks the progress of iterating over a matrix in its `x` and `y` properties. The `next` method starts by checking whether the bottom of the matrix has been reached. If it hasn't, it _first_ creates the object holding the current value and _then_ updates its position, moving to the next row if necessary.
|
||
|
||
-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 [downloadable](http://eloquentjavascript.net/2nd_edition/code/mountains.js) from the website.
|
||
-
|
||
-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.
|
||
+Let us set up the `Matrix` class to be iterable. Throughout this book, I'll occasionally use after-the-fact prototype manipulation to add methods to classes, so that the individual pieces of code remain small and self-contained. In a regular program, where there is no need to split the code into small pieces, you'd declare these methods directly in the class instead.
|
||
|
||
```
|
||
-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)]);
|
||
+Matrix.prototype[Symbol.iterator] = function() {
|
||
+ return new MatrixIterator(this);
|
||
};
|
||
```
|
||
|
||
-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.
|
||
-
|
||
-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.
|
||
-
|
||
-Having an underlining mechanism, we can now write a function that builds up a grid of cells from our data set.
|
||
+We can now loop over a matrix with `for`/`of`.
|
||
|
||
```
|
||
-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);
|
||
+let matrix = new Matrix(2, 2, (x, y) => `value ${x},${y}`);
|
||
+for (let {x, y, value} of matrix) {
|
||
+ console.log(x, y, value);
|
||
}
|
||
-
|
||
-console.log(drawTable(dataTable(MOUNTAINS)));
|
||
-// → name height country
|
||
-// ------------ ------ -------------
|
||
-// Kilimanjaro 5895 Tanzania
|
||
-// … etcetera
|
||
+// → 0 0 value 0,0
|
||
+// → 1 0 value 1,0
|
||
+// → 0 1 value 0,1
|
||
+// → 1 1 value 1,1
|
||
```
|
||
|
||
-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.
|
||
-
|
||
-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
|
||
-
|
||
-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.
|
||
+## Getters, setters, and statics
|
||
|
||
-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.
|
||
+Interfaces often consist mostly of methods, but it is also okay to include properties that hold non-function values. For example, `Map` objects have a `size` property that tells you how many keys are stored in them.
|
||
|
||
-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.
|
||
+It is not even necessary for such an object to compute and store such a property directly in the instance. Even properties that are accessed directly may hide a method call. Such methods are called _getters_, and they are defined by writing `get` in front of the method name in an object expression or class declaration.
|
||
|
||
```
|
||
-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);
|
||
+let varyingSize = {
|
||
+ get size() {
|
||
+ return Math.floor(Math.random() * 100);
|
||
}
|
||
};
|
||
|
||
-console.log(pile.height);
|
||
-// → 3
|
||
-pile.height = 100;
|
||
-// → Ignoring attempt to set height to 100
|
||
+console.log(varyingSize.size);
|
||
+// → 73
|
||
+console.log(varyingSize.size);
|
||
+// → 49
|
||
```
|
||
|
||
-In an 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).
|
||
+Whenever someone reads from this object's `size` property, the associated method is called. You can do a similar thing when a property is written to, using a _setter_.
|
||
|
||
```
|
||
-Object.defineProperty(TextCell.prototype, "heightProp", {
|
||
- get: function() { return this.text.length; }
|
||
-});
|
||
+class Temperature {
|
||
+ constructor(celsius) {
|
||
+ this.celsius = celsius;
|
||
+ }
|
||
+ get fahrenheit() {
|
||
+ return this.celsius * 1.8 + 32;
|
||
+ }
|
||
+ set fahrenheit(value) {
|
||
+ this.celsius = (value - 32) / 1.8;
|
||
+ }
|
||
+
|
||
+ static fromFahrenheit(value) {
|
||
+ return new Temperature((value - 32) / 1.8);
|
||
+ }
|
||
+}
|
||
|
||
-var cell = new TextCell("no\nway");
|
||
-console.log(cell.heightProp);
|
||
-// → 2
|
||
-cell.heightProp = 100;
|
||
-console.log(cell.heightProp);
|
||
-// → 2
|
||
+let temp = new Temperature(22);
|
||
+console.log(temp.fahrenheit);
|
||
+// → 71.6
|
||
+temp.fahrenheit = 86;
|
||
+console.log(temp.celsius);
|
||
+// → 30
|
||
```
|
||
|
||
-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.
|
||
+The `Temperature` class allows you to read and write the temperature in either degrees Celsius or degrees Fahrenheit, but internally only stores Celsius, and automatically converts to Celsius in the `fahrenheit` getter and setter.
|
||
|
||
-## Inheritance
|
||
+Sometimes you want to attach some properties directly to your constructor function, rather than to the prototype. Such methods won't have access to a class instance but can, for example, be used to provide additional ways to create instances.
|
||
|
||
-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.
|
||
+Inside a class declaration, methods that have `static` written before their name are stored on the constructor. So the `Temperature` class allows you to write `Temperature.<wbr>fromFahrenheit(100)` to create a temperature using degrees Fahrenheit.
|
||
|
||
-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.
|
||
+## Inheritance
|
||
|
||
-```
|
||
-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;
|
||
-};
|
||
-```
|
||
+Some matrices are known to be _symmetric_. If you mirror a symmetric matrix around its top-left-to-bottom-right diagonal, it stays the same. In other words, the value stored at _x_,_y_ is always the same as that at _y_,_x_.
|
||
|
||
-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.
|
||
+Imagine we need a data structure like `Matrix` but one that enforces the fact that the matrix is and remains symmetrical. We could write it from scratch, but that would involve repeating some code very similar to what we already wrote.
|
||
|
||
-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.
|
||
+JavaScript's prototype system makes it possible to create a _new_ class, much like the old class, but with new definitions for some of its properties. The prototype for the new class derives from the old prototype but adds a new definition for, say, the `set` method.
|
||
|
||
-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.
|
||
+In object-oriented programming terms, this is called _inheritance_. The new class inherits properties and behavior from the old class.
|
||
|
||
```
|
||
-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));
|
||
+class SymmetricMatrix extends Matrix {
|
||
+ constructor(size, element = (x, y) => undefined) {
|
||
+ super(size, size, (x, y) => {
|
||
+ if (x < y) return element(y, x);
|
||
+ else return element(x, y);
|
||
});
|
||
- });
|
||
- return [headers].concat(body);
|
||
+ }
|
||
+
|
||
+ set(x, y, value) {
|
||
+ super.set(x, y, value);
|
||
+ if (x != y) {
|
||
+ super.set(y, x, value);
|
||
+ }
|
||
+ }
|
||
}
|
||
|
||
-console.log(drawTable(dataTable(MOUNTAINS)));
|
||
-// → … beautifully aligned table
|
||
+let matrix = new SymmetricMatrix(5, (x, y) => `${x},${y}`);
|
||
+console.log(matrix.get(2, 3));
|
||
+// → 3,2
|
||
```
|
||
|
||
-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.
|
||
+The use of the word `extends` indicates that this class shouldn't be directly based on the default `Object` prototype, but on some other class. This is called the _superclass_. The derived class is the _subclass_.
|
||
+
|
||
+To initialize a `SymmetricMatrix` instance, the constructor calls its superclass' constructor through the `super` keyword. This is necessary because if this new object is to behave (roughly) like a `Matrix`, it is going to need the instance properties that matrices have. In order to ensure the matrix is symmetrical, the constructor wraps the `content` method to swap the coordinates for values below the diagonal.
|
||
|
||
-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.
|
||
+The `set` method again uses `super`, but this time not to call the constructor, but to call a specific method from the superclass' set of methods. We are redefining `set` but do want to use the original behavior. Because `this.set` refers to the _new_ `set` method, calling that wouldn't work. Inside class methods, `super` provides a way to call methods as they were defined in the superclass.
|
||
|
||
-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 methods.
|
||
+Inheritance allows us to build slightly different data types from existing data types with relatively little work. It 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 more controversial.
|
||
+
|
||
+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 classes together, creating _more_ tangle. When inheriting from a class, you usually have to know more about how it works than when simply using it. Inheritance can be a useful tool, and I use it now and then in my own programs, but it shouldn't be the first tool you reach for, and you probably shouldn't actively go looking for opportunities to construct class hierarchies (family trees of classes).
|
||
|
||
## The instanceof operator
|
||
|
||
-It is occasionally useful to know whether an object was derived from a specific constructor. For this, JavaScript provides a binary operator called `instanceof`.
|
||
+It is occasionally useful to know whether an object was derived from a specific class. For this, JavaScript provides a binary operator called `instanceof`.
|
||
|
||
```
|
||
-console.log(new RTextCell("A") instanceof RTextCell);
|
||
+console.log(
|
||
+ new SymmetricMatrix(2) instanceof SymmetricMatrix);
|
||
// → true
|
||
-console.log(new RTextCell("A") instanceof TextCell);
|
||
+console.log(new SymmetricMatrix(2) instanceof Matrix);
|
||
// → true
|
||
-console.log(new TextCell("A") instanceof RTextCell);
|
||
+console.log(new Matrix(2, 2) instanceof SymmetricMatrix);
|
||
// → false
|
||
console.log([1] instanceof Array);
|
||
// → true
|
||
```
|
||
|
||
-The operator will 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`.
|
||
+The operator will see through inherited types, so a `SymmetricMatrix` is an instance of `Matrix`. The operator can also be applied to standard constructors like `Array`. Almost every object is an instance of `Object`.
|
||
|
||
## Summary
|
||
|
||
-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 `Object.prototype` as their prototype.
|
||
+So objects do more than just hold their own properties. They have prototypes, which are other objects. They'll act as if they have properties they don't have as long as their prototype has that property. Simple objects have `Object.prototype` as their prototype.
|
||
+
|
||
+Constructors, which are functions whose names usually start 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. You can make good use of this by putting the properties that all values of a given type share into their prototype. There's a `class` notation that provides a clear way to define a constructor and its prototype.
|
||
|
||
-Constructors, which are functions whose names usually start 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.
|
||
+You can define getters and setters to secretly call methods every time an object's property is accessed. Static methods are methods stored in a class' constructor, rather than its prototype.
|
||
+
|
||
+The `instanceof` operator can, given an object and a constructor, tell you whether that object is an instance of that constructor.
|
||
|
||
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 _encapsulated_, hidden behind the interface.
|
||
|
||
-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.
|
||
+More than one type may implement the same interface. Code written to use an interface automatically knows how to work with any number of different objects that provide the interface. This is called _polymorphism_.
|
||
|
||
-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.
|
||
+When implementing multiple classes that differ in only some details, it can be helpful to write the new classes as _subclasses_ of an existing class, _inheriting_ part of its behavior.
|
||
|
||
## Exercises
|
||
|
||
### A vector type
|
||
|
||
-Write a constructor `Vector` that represents a vector in two-dimensional space. It takes `x` and `y` parameters (numbers), which it should save to properties of the same name.
|
||
+Write a class `Vec` that represents a vector in two-dimensional space. It takes `x` and `y` parameters (numbers), which it should save to properties of the same name.
|
||
|
||
-Give the `Vector` prototype two methods, `plus` and `minus`, 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 `this` and the parameter) _x_ and _y_ values.
|
||
+Give the `Vec` prototype two methods, `plus` and `minus`, that take another vector as a parameter and return a new vector that has the sum or difference of the two vectors' (`this` and the parameter) _x_ and _y_ values.
|
||
|
||
Add a getter property `length` to the prototype that computes the length of the vector—that is, the distance of the point (_x_, _y_) from the origin (0, 0).
|
||
|
||
```
|
||
// Your code here.
|
||
|
||
-console.log(new Vector(1, 2).plus(new Vector(2, 3)));
|
||
-// → Vector{x: 3, y: 5}
|
||
-console.log(new Vector(1, 2).minus(new Vector(2, 3)));
|
||
-// → Vector{x: -1, y: -1}
|
||
-console.log(new Vector(3, 4).length);
|
||
+console.log(new Vec(1, 2).plus(new Vec(2, 3)));
|
||
+// → Vec{x: 3, y: 5}
|
||
+console.log(new Vec(1, 2).minus(new Vec(2, 3)));
|
||
+// → Vec{x: -1, y: -1}
|
||
+console.log(new Vec(3, 4).length);
|
||
// → 5
|
||
```
|
||
|
||
-Your solution can follow the pattern of the `Rabbit` constructor from this chapter quite closely.
|
||
+Look back to the `Rabbit` class example if you're unsure how `class` declarations look.
|
||
+
|
||
+Adding a getter property to the constructor can be done by putting the word `get` before the method name. 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 `Math.sqrt` is the way you compute a square root in JavaScript.
|
||
+
|
||
+### Groups
|
||
+
|
||
+The standard JavaScript environment provides another data structure called `Set`. Like an instance of `Map`, a set holds a collection of values. Unlike `Map`, it does not associate other values with those—it just tracks which values are part of the set. A value can only be part of a set once—adding it again doesn't have any effect.
|
||
|
||
-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), 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 `Math.sqrt` is the way you compute a square root in JavaScript.
|
||
+Write a class called `Group` (since `Set` is already taken). Like `Set`, it has `add`, `delete`, and `has` methods. Its constructor creates an empty group, `add` adds a value to the group (but only if it isn't already a member), `delete` removes its argument from the group (if it was a member), and `has` returns a Boolean value indicating whether its argument is a member of the group.
|
||
|
||
-### Another cell
|
||
+Use the `===` operator, or something equivalent such as `indexOf`, to determine whether two values are the same.
|
||
|
||
-Implement a cell type named `StretchCell(inner, width, height)` that conforms to the [table cell interface](06_object.html#table_interface) described earlier in the chapter. It should wrap another cell (like `UnderlinedCell` does) and ensure that the resulting cell has at least the given `width` and `height`, even if the inner cell would naturally be smaller.
|
||
+Give the class a static `from` method that takes an iteratable object as argument and creates a group that contains all the values produced by iterating over it.
|
||
|
||
```
|
||
-// Your code here.
|
||
+class Group {
|
||
+ // Your code here.
|
||
+}
|
||
|
||
-var sc = new StretchCell(new TextCell("abc"), 1, 2);
|
||
-console.log(sc.minWidth());
|
||
-// → 3
|
||
-console.log(sc.minHeight());
|
||
-// → 2
|
||
-console.log(sc.draw(3, 2));
|
||
-// → ["abc", " "]
|
||
+let group = Group.from([10, 20]);
|
||
+console.log(group.has(10));
|
||
+// → true
|
||
+console.log(group.has(30));
|
||
+// → false
|
||
+group.add(10);
|
||
+group.delete(10);
|
||
+console.log(group.has(10));
|
||
+// → false
|
||
```
|
||
|
||
-You'll have to store all three constructor arguments in the instance object. The `minWidth` and `minHeight` methods should call through to the corresponding methods in the `inner` cell but ensure that no number less than the given size is returned (possibly using `Math.max`).
|
||
+The easiest way to do this is to store an array of group members in an instance property. The `includes` or `indexOf` methods can be used to check whether a given value is in the array.
|
||
|
||
-Don't forget to add a `draw` method that simply forwards the call to the inner cell.
|
||
+Your class' constructor can set the member collection to an empty array. When `add` is called, it must check whether the given value is in the array, and add it, for example with `push`, otherwise.
|
||
|
||
-### Sequence interface
|
||
+Deleting an element from an array, in `delete`, is less straightforward, but you can use `filter` to create a new array without the value. Don't forget to overwrite the property holding the members with the newly filtered version of the array.
|
||
|
||
-Design an _interface_ 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.
|
||
+The `from` method can use a `for`/`of` loop to get the values out of the iterable object and call `add` to put them into a newly created group.
|
||
|
||
-When you have specified your interface, try to write a function `logFive` that takes a sequence object and calls `console.log` on its first five elements—or fewer, if the sequence has fewer than five elements.
|
||
+### Iterable groups
|
||
|
||
-Then implement an object type `ArraySeq` that wraps an array and allows iteration over the array using the interface you designed. Implement another object type `RangeSeq` that iterates over a range of integers (taking `from` and `to` arguments to its constructor) instead.
|
||
+Make the `Group` class from the previous exercise iterable. Refer back to the section about the iterator interface earlier in the chapter if you aren't clear on the exact form of the interface anymore.
|
||
+
|
||
+If you used an array to represent the group's members, don't just return the iterator created by calling the `Symbol.iterator` method on the array. That would work, but it defeats the purpose of this exercise.
|
||
+
|
||
+It is okay if your iterator behaves strangely when the group is modified during iteration.
|
||
|
||
```
|
||
-// Your code here.
|
||
+// Your code here (and the code from the previous exercise)
|
||
+
|
||
+for (let value of Group.from(["a", "b", "c"])) {
|
||
+ console.log(value);
|
||
+}
|
||
+// → a
|
||
+// → b
|
||
+// → c
|
||
+```
|
||
+
|
||
+It is probably worthwhile to define a new class `GroupIterator`. Iterator instances should have a property that tracks the current position in the group. Every time `next` is called, it checks whether it is done, and if not, moves past the current value and returns it.
|
||
+
|
||
+The `Group` class itself gets a method named by `Symbol.iterator` that, when called, returns a new instance of the iterator class for that group.
|
||
+
|
||
+### Borrowing a method
|
||
+
|
||
+Earlier in the chapter I mentioned that an object's `hasOwnProperty` can be used as a more robust alternative to the `in` operator when you want to ignore the prototype's properties. But what if your map needs to include the word `"hasOwnProperty"`? You won't be able to call that method anymore, because the object's own property hides the method value.
|
||
+
|
||
+Can you think of a way to call `hasOwnProperty` on an object that has its own property by that name?
|
||
|
||
-logFive(new ArraySeq([1, 2]));
|
||
-// → 1
|
||
-// → 2
|
||
-logFive(new RangeSeq(100, 1000));
|
||
-// → 100
|
||
-// → 101
|
||
-// → 102
|
||
-// → 103
|
||
-// → 104
|
||
```
|
||
+let map = {one: true, two: true, hasOwnProperty: true};
|
||
|
||
-One way to solve this is to give the sequence objects _state_, 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.
|
||
+// Fix this call
|
||
+console.log(map.hasOwnProperty("one"));
|
||
+// → true
|
||
+```
|
||
|
||
-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, `next`, which returns `null` or `undefined` when the sequence is at its end. But now you have a problem when a sequence actually contains `null`. So a separate method (or getter property) to find out whether the end has been reached is probably preferable.
|
||
+Remember that methods that exist on plain objects come from `Object.prototype`.
|
||
|
||
-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.
|
||
+And that you can call a function with a specific `this` binding by using its `call` method.
|