ok
|
@ -1,23 +1,23 @@
|
||||||
|
|
||||||
# Object.keys, values, entries
|
# Object.keys, values, entries
|
||||||
|
|
||||||
|
Let's step away from the indivitual data structures and talk about the iterations over them.
|
||||||
|
|
||||||
In the previous chapter we saw methods `map.keys()`, `map.values()`, `map.entries()`.
|
In the previous chapter we saw methods `map.keys()`, `map.values()`, `map.entries()`.
|
||||||
|
|
||||||
These methods are generic, there is a common agreement to use them for data structures.
|
These methods are generic, there is a common agreement to use them for data structures. If we ever create a data structure of our own, we should implement them too.
|
||||||
|
|
||||||
They are supported for:
|
They are supported for:
|
||||||
|
|
||||||
- `Map`
|
- `Map`
|
||||||
- `Set`
|
- `Set`
|
||||||
- `Array` (without `arr.values()`, because that would be repeating itself)
|
- `Array` (except `arr.values()`)
|
||||||
|
|
||||||
If we ever create a data structure of our own, we should implement them too.
|
Plain objects also support similar methods, but the syntax is a bit different.
|
||||||
|
|
||||||
## Object.keys, values, entries
|
## Object.keys, values, entries
|
||||||
|
|
||||||
For plain objects, situation is a little bit different.
|
For plain objects, the following methods are available:
|
||||||
|
|
||||||
There are similar methods:
|
|
||||||
|
|
||||||
- [Object.keys(obj)](mdn:js/Object/keys) -- returns an array of keys.
|
- [Object.keys(obj)](mdn:js/Object/keys) -- returns an array of keys.
|
||||||
- [Object.values(obj)](mdn:js/Object/values) -- returns an array of values.
|
- [Object.values(obj)](mdn:js/Object/values) -- returns an array of values.
|
||||||
|
@ -30,8 +30,11 @@ There are similar methods:
|
||||||
| Call syntax | `map.keys()` | `Object.keys(obj)`, but not `obj.keys()` |
|
| Call syntax | `map.keys()` | `Object.keys(obj)`, but not `obj.keys()` |
|
||||||
| Returns | iterable | "real" Array |
|
| Returns | iterable | "real" Array |
|
||||||
|
|
||||||
1. The reason for call syntax `Object.keys(obj)` is flexibility. We can have an object of our own like `order` that implements its own `order.values()` method. And we still can call `Object.values(order)` on it.
|
The first difference is that we have to call `Object.keys(obj)`, and not `obj.keys()`.
|
||||||
2. ...And the returned value is not just an iterable, but an Array for historical reasons.
|
|
||||||
|
Why so? There main reason is flexibility. Remember, objects are a base of all complex structures in Javascript. So we may have an object of our own like `order` that implements its own `order.values()` method. And we still can call `Object.values(order)` on it.
|
||||||
|
|
||||||
|
The second difference is that `Object.*` methods return "real" array objects, not just an iterable. That's mainly for historical reasons.
|
||||||
|
|
||||||
For instance:
|
For instance:
|
||||||
|
|
||||||
|
@ -46,7 +49,7 @@ let user = {
|
||||||
- `Object.values(user) = ["John", 30]`
|
- `Object.values(user) = ["John", 30]`
|
||||||
- `Object.entries(user) = [ ["name","John"], ["age",30] ]`
|
- `Object.entries(user) = [ ["name","John"], ["age",30] ]`
|
||||||
|
|
||||||
We can also `Object.values` for a loop over property values:
|
Here's an example of using `Object.values` to loop over property values:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
let user = {
|
let user = {
|
||||||
|
@ -63,5 +66,5 @@ for(let value of Object.values(user)) {
|
||||||
```smart header="`Object.keys/values/entries` ignore symbolic properties"
|
```smart header="`Object.keys/values/entries` ignore symbolic properties"
|
||||||
Just like `for..in` loop, these methods ignore properties that use `Symbol(...)` as keys.
|
Just like `for..in` loop, these methods ignore properties that use `Symbol(...)` as keys.
|
||||||
|
|
||||||
Usually that's convenient. There is a separate method named [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols) that returns an array of only symbolic keys (if we really know what we're doing). Also, the method [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) returns *all* keys.
|
Usually that's convenient. But if we want symbolic keys too, then there's a separate method [Object.getOwnPropertySymbols](mdn:js/Object/getOwnPropertySymbols) that returns an array of only symbolic keys. Also, the method [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) returns *all* keys.
|
||||||
```
|
```
|
||||||
|
|
|
@ -1,6 +1,10 @@
|
||||||
# Destructuring assignment
|
# Destructuring assignment
|
||||||
|
|
||||||
*Destructuring assignment* is a special syntax that allows to "unpack" arrays or objects into a bunch of variables, that are sometimes more convenient to work. Destructuring also works great with complex functions that have a lot of parameters, default values etc.
|
The two most used data structures in Javascript are `Object` and `Array`.
|
||||||
|
|
||||||
|
Objects allow to pack many pieces of information into a single entity and arrays allow to store ordered collections. So we can make an object or an array and handle it as a single thing, maybe pass to a function call.
|
||||||
|
|
||||||
|
*Destructuring assignment* is a special syntax that allows to "unpack" arrays or objects into a bunch of variables, as sometimes they are more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and soon we'll see how these are handled too.
|
||||||
|
|
||||||
[cut]
|
[cut]
|
||||||
|
|
||||||
|
@ -94,7 +98,9 @@ let user = {
|
||||||
};
|
};
|
||||||
|
|
||||||
// loop over keys-and-values
|
// loop over keys-and-values
|
||||||
|
*!*
|
||||||
for(let [key, value] of Object.entries(user)) {
|
for(let [key, value] of Object.entries(user)) {
|
||||||
|
*/!*
|
||||||
alert(`${key}:${value}`); // name:John, then age:30
|
alert(`${key}:${value}`); // name:John, then age:30
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -106,7 +112,9 @@ let user = new Map();
|
||||||
user.set("name", "John");
|
user.set("name", "John");
|
||||||
user.set("age", "30");
|
user.set("age", "30");
|
||||||
|
|
||||||
|
*!*
|
||||||
for(let [key, value] of user.entries()) {
|
for(let [key, value] of user.entries()) {
|
||||||
|
*/!*
|
||||||
alert(`${key}:${value}`); // name:John, then age:30
|
alert(`${key}:${value}`); // name:John, then age:30
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
|
@ -330,8 +330,8 @@ Now it works, because the name `"func"` is function-local. It is not taken from
|
||||||
|
|
||||||
The outer code still has it's variable `sayHi` or `welcome` later. And `func` is an "internal function name", how it calls itself privately.
|
The outer code still has it's variable `sayHi` or `welcome` later. And `func` is an "internal function name", how it calls itself privately.
|
||||||
|
|
||||||
```smart header="No such thing for Function Declaration"
|
```smart header="There's no such thing for Function Declaration"
|
||||||
The "internal name" feature described here is only available for Function Expressions, not to Function Declarations. For Function Declarations, there's just no syntax possibility to add a one more "internal" name for them.
|
The "internal name" feature described here is only available for Function Expressions, not to Function Declarations. For Function Declarations, there's just no syntax possibility to add a one more "internal" name.
|
||||||
|
|
||||||
Sometimes, when we need a reliable internal name, it's the reason to rewrite a Function Declaration to Named Function Expression form.
|
Sometimes, when we need a reliable internal name, it's the reason to rewrite a Function Declaration to Named Function Expression form.
|
||||||
```
|
```
|
||||||
|
|
|
@ -46,6 +46,99 @@ That's the resulting picture:
|
||||||
|
|
||||||
On the picture, `"prototype"` is a horizontal arrow, it's a regular property, and `[[Prototype]]` is vertical, meaning the inheritance of `rabbit` from `animal`.
|
On the picture, `"prototype"` is a horizontal arrow, it's a regular property, and `[[Prototype]]` is vertical, meaning the inheritance of `rabbit` from `animal`.
|
||||||
|
|
||||||
|
|
||||||
|
## Default F.prototype, constructor property
|
||||||
|
|
||||||
|
Every function has the `"prototype"` property even if we don't supply it.
|
||||||
|
|
||||||
|
The default `"prototype"` is an object with the only property `constructor` that points back to the function itself.
|
||||||
|
|
||||||
|
Like this:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function Rabbit() {}
|
||||||
|
|
||||||
|
/* default prototype
|
||||||
|
Rabbit.prototype = { constructor: Rabbit };
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
We can check it:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
function Rabbit() {}
|
||||||
|
// by default:
|
||||||
|
// Rabbit.prototype = { constructor: Rabbit }
|
||||||
|
|
||||||
|
alert( Rabbit.prototype.constructor == Rabbit ); // true
|
||||||
|
```
|
||||||
|
|
||||||
|
Naturally, it we do nothing, the `constructor` property is available to all rabbits through `[[Prototype]]`:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
function Rabbit() {}
|
||||||
|
// by default:
|
||||||
|
// Rabbit.prototype = { constructor: Rabbit }
|
||||||
|
|
||||||
|
let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}
|
||||||
|
|
||||||
|
alert(rabbit.constructor == Rabbit); // true (from prototype)
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
We can use `constructor` to create a new object using the same constructor as the existing one.
|
||||||
|
|
||||||
|
Like here:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
function Rabbit(name) {
|
||||||
|
this.name = name;
|
||||||
|
alert(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
let rabbit = new Rabbit("White Rabbit");
|
||||||
|
|
||||||
|
let rabbit2 = new rabbit.constructor("Black Rabbit");
|
||||||
|
```
|
||||||
|
|
||||||
|
That's handy when we have an object, don't know which constructor was used for it (e.g. it comes from a 3rd party library), and we need to create the same.
|
||||||
|
|
||||||
|
...But probably the most important thing about `"constructor"` is that...
|
||||||
|
|
||||||
|
**JavaScript itself does not use the `"constructor"` property at all.**
|
||||||
|
|
||||||
|
Yes, it exists in the default `"prototype"` for functions, but that's literally all about it. No language function relies on it and nothing controls its validity.
|
||||||
|
|
||||||
|
It is created automatically, but what happens with it later -- is totally on us.
|
||||||
|
|
||||||
|
In particular, if we replace the default prototype by assigning our own `Rabbit.prototype = { jumps: true }`, then there will be no `"constructor"` in it.
|
||||||
|
|
||||||
|
Such assignment won't break native methods or syntax, because nothing in the language uses the `"constructor"` property. But we may want to keep `"constructor"` for convenience by adding properties to the default `"prototype"` instead of overwriting it as a whole:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function Rabbit() {}
|
||||||
|
|
||||||
|
// Not overwrite Rabbit.prototype totally
|
||||||
|
// just add to it
|
||||||
|
Rabbit.prototype.jumps = true
|
||||||
|
// the default Rabbit.prototype.constructor is preserved
|
||||||
|
```
|
||||||
|
|
||||||
|
Or, alternatively, recreate it manually:
|
||||||
|
|
||||||
|
```js
|
||||||
|
Rabbit.prototype = {
|
||||||
|
jumps: true,
|
||||||
|
*!*
|
||||||
|
constructor: Rabbit
|
||||||
|
*/!*
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Summary
|
## Summary
|
||||||
|
|
||||||
In this chapter we briefly described the way of setting a `[[Prototype]]` for objects created via a constructor function. Later we'll see more advanced programming patterns that rely on it.
|
In this chapter we briefly described the way of setting a `[[Prototype]]` for objects created via a constructor function. Later we'll see more advanced programming patterns that rely on it.
|
||||||
|
@ -64,3 +157,5 @@ let user = {
|
||||||
prototype: "Bla-bla" // no magic at all
|
prototype: "Bla-bla" // no magic at all
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
By default all functions have `F.prototype = { constructor: F }`. So by default we can get the constructor of an object by accessing its `"constructor"` property.
|
||||||
|
|
Before Width: | Height: | Size: 9.8 KiB After Width: | Height: | Size: 9.4 KiB |
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 15 KiB |
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 36 KiB |
|
@ -19,7 +19,7 @@ dictionary.__proto__ = "test";
|
||||||
|
|
||||||
// apple and __proto__ is in the loop
|
// apple and __proto__ is in the loop
|
||||||
for(let key in dictionary) {
|
for(let key in dictionary) {
|
||||||
alert(key); // "apple", then "__proto"
|
alert(key); // "apple", then "__proto__"
|
||||||
}
|
}
|
||||||
|
|
||||||
// comma-separated list of properties by toString
|
// comma-separated list of properties by toString
|
|
@ -6,24 +6,27 @@ importance: 5
|
||||||
|
|
||||||
There's an object `dictionary`, suited to store any `key/value` pairs.
|
There's an object `dictionary`, suited to store any `key/value` pairs.
|
||||||
|
|
||||||
Add `toString` for it, that would show a list of comma-delimited keys. The method itself should not show up in `for..in` over the object.
|
Add `toString` for it, that would show a list of comma-delimited keys. Your `toString` should not show up in `for..in` over the object.
|
||||||
|
|
||||||
Here's how it should work:
|
Here's how it should work:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
let dictionary = Object.create(null);
|
let dictionary = Object.create(null);
|
||||||
|
|
||||||
|
*!*
|
||||||
// your code to add toString
|
// your code to add toString
|
||||||
|
*/!*
|
||||||
|
|
||||||
|
// add some data
|
||||||
dictionary.apple = "Apple";
|
dictionary.apple = "Apple";
|
||||||
dictionary.__proto__ = "test";
|
dictionary.__proto__ = "test";
|
||||||
|
|
||||||
// apple and __proto__ is in the loop
|
// only apple and __proto__ are in the loop
|
||||||
for(let key in dictionary) {
|
for(let key in dictionary) {
|
||||||
alert(key); // "apple", then "__proto"
|
alert(key); // "apple", then "__proto__"
|
||||||
}
|
}
|
||||||
|
|
||||||
// comma-separated list of properties by toString
|
// your toString in action
|
||||||
alert(dictionary); // "apple,__proto__"
|
alert(dictionary); // "apple,__proto__"
|
||||||
```
|
```
|
||||||
|
|
|
@ -39,6 +39,6 @@ Here's how `new user.constructor('Pete')` works:
|
||||||
|
|
||||||
1. First, it looks for `constructor` in `user`. Nothing.
|
1. First, it looks for `constructor` in `user`. Nothing.
|
||||||
2. Then it follows the prototype chain. The prototype of `user` is `User.prototype`, and it also has nothing.
|
2. Then it follows the prototype chain. The prototype of `user` is `User.prototype`, and it also has nothing.
|
||||||
3. The value of `User.prototype` is a plain object `{}`, it's prototype is `Object.prototype`. And there is `Object.prototype.constructor == Object`. So it is used.
|
3. The value of `User.prototype` is a plain object `{}`, its prototype is `Object.prototype`. And there is `Object.prototype.constructor == Object`. So it is used.
|
||||||
|
|
||||||
At the end, we have `let user2 = new Object('Pete')`. The built-in `Object` constructor ignores arguments, it always creates an empty object -- that's what we have in `user2` after all.
|
At the end, we have `let user2 = new Object('Pete')`. The built-in `Object` constructor ignores arguments, it always creates an empty object -- that's what we have in `user2` after all.
|
|
@ -1,14 +1,55 @@
|
||||||
|
|
||||||
# Native prototypes
|
# Native prototypes
|
||||||
|
|
||||||
All built-in objects such as `Array`, `Date`, `Function` and others also keep methods in prototypes.
|
The `"prototype"` property is widely used by the core of Javascript itself. All built-in constructor functions use it.
|
||||||
|
|
||||||
For instance, when we create an array, `[1, 2, 3]`, the default `new Array()` constructor is used internally. So the array data is written into the new object, and `Array.prototype` becomes its prototype and provides methods. That's very memory-efficient.
|
We'll see how it is for plain objects first, and then for more complex ones.
|
||||||
|
|
||||||
|
## Object.prototype
|
||||||
|
|
||||||
|
Let's say we output an empty object:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
let obj = {};
|
||||||
|
alert( obj ); // "[object Object]" ?
|
||||||
|
```
|
||||||
|
|
||||||
|
Where's the code that generates the string `"[object Object]"`? That's a built-in `toString` method, but where is it? The `obj` is empty!
|
||||||
|
|
||||||
|
...But the short notation `obj = {}` is the same as `obj = new Object()`, where `Object` -- is a built-in object constructor function. And that function has `Object.prototype` that references a huge object with `toString` and other functions.
|
||||||
|
|
||||||
|
Like this (all that is built-in):
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
When `new Object()` is called (or a literal object `{...}` is created), the `[[Prototype]]` of it is set to `Object.prototype` by the rule that we've discussed in the previous chapter:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Afterwards when `obj.toString()` is called -- the method is taken from `Object.prototype`.
|
||||||
|
|
||||||
|
We can check it like this:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
let obj = {};
|
||||||
|
|
||||||
|
alert(obj.__proto__ === Object.prototype); // true
|
||||||
|
// obj.toString === obj.__proto__toString == Object.prototype.toString
|
||||||
|
```
|
||||||
|
|
||||||
|
Please note that there is no additional `[[Prototype]]` in the chain above `Object.prototype`:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
alert(Object.prototype.__proto__); // null
|
||||||
|
```
|
||||||
|
|
||||||
|
## Other built-in prototypes
|
||||||
|
|
||||||
|
Other built-in objects such as `Array`, `Date`, `Function` and others also keep methods in prototypes.
|
||||||
|
|
||||||
|
For instance, when we create an array `[1, 2, 3]`, the default `new Array()` constructor is used internally. So the array data is written into the new object, and `Array.prototype` becomes its prototype and provides methods. That's very memory-efficient.
|
||||||
|
|
||||||
By specification, all built-in prototypes have `Object.prototype` on the top. Sometimes people say that "everything inherits from objects".
|
By specification, all built-in prototypes have `Object.prototype` on the top. Sometimes people say that "everything inherits from objects".
|
||||||
|
|
||||||
[cut]
|
|
||||||
|
|
||||||
Here's the overall picture (for 3 built-ins to fit):
|
Here's the overall picture (for 3 built-ins to fit):
|
||||||
|
|
||||||

|

|
After Width: | Height: | Size: 9.4 KiB |
After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 44 KiB After Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 105 KiB After Width: | Height: | Size: 105 KiB |
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 4 KiB After Width: | Height: | Size: 4 KiB |
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 9.1 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 36 KiB |
Before Width: | Height: | Size: 9.8 KiB |
Before Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 34 KiB |
|
@ -1 +0,0 @@
|
||||||
<svg width="200" height="233" viewBox="0 0 200 233" xmlns="http://www.w3.org/2000/svg"><title>native-prototype-object</title><g fill="none" fill-rule="evenodd"><path stroke="#979797" d="M0 86h200v60H0z"/><text font-family="Consolas" font-size="14" fill="#000" transform="translate(0 69)"><tspan x="11" y="41">toString: function</tspan> <tspan x="11" y="57">другие методы объектов</tspan></text><text font-family="Consolas" font-size="14" font-style="italic" fill="#000" transform="translate(0 69)"><tspan x="0" y="10">Object.prototype</tspan></text><path stroke="#979797" d="M0 203h200v30H0z"/><text font-family="Consolas" font-size="14" font-style="italic" fill="#000" transform="translate(0 186)"><tspan x="0" y="10">obj</tspan></text><path d="M60.5 194.5v-41m0 0l-3 10.8h6l-3-10.8z" stroke="#4990E2" stroke-linecap="square" fill="#4990E2"/><text font-family="Consolas" font-size="14" fill="#4990E2"><tspan x="70" y="175">__proto__</tspan></text><path d="M60.5 62.5v-41m0 0l-3 10.8h6l-3-10.8z" stroke="#4990E2" stroke-linecap="square" fill="#4990E2"/><text font-family="Consolas" font-size="14" fill="#4990E2"><tspan x="70" y="43">__proto__</tspan></text><text font-family="Consolas" font-size="14" fill="#4990E2"><tspan x="46" y="10">null</tspan></text></g></svg>
|
|
Before Width: | Height: | Size: 1.3 KiB |
Before Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 105 KiB |
Before Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 30 KiB |
|
@ -1,106 +1,5 @@
|
||||||
# Object.prototype and methods
|
|
||||||
|
|
||||||
The `"prototype"` property is widely used by the core of Javascript itself. All built-in constructor functions use it.
|
# Methods for prototypes
|
||||||
|
|
||||||
We'll see how it is for plain objects first, and then for more complex ones.
|
|
||||||
|
|
||||||
Let's say we output an empty object:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let obj = {};
|
|
||||||
alert( obj ); // "[object Object]" ?
|
|
||||||
```
|
|
||||||
|
|
||||||
Where's the code that generates the string `"[object Object]"`? That's a built-in `toString` method, but where is it? The `obj` is empty!
|
|
||||||
|
|
||||||
...But the short notation `obj = {}` is the same as `obj = new Object()`, where `Object` -- is a built-in object constructor function. And that function has `Object.prototype` that references a huge object with `toString` and other functions.
|
|
||||||
|
|
||||||
Like this (all that is built-in):
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
When `new Object()` is called (or a literal object `{...}` is created), the `[[Prototype]]` of it is set to `Object.prototype` by the rule that we've discussed in the previous chapter:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Afterwards when `obj.toString()` is called -- the method is taken from `Object.prototype`.
|
|
||||||
|
|
||||||
We can check it like this:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let obj = {};
|
|
||||||
|
|
||||||
alert(obj.__proto__ === Object.prototype); // true
|
|
||||||
// obj.toString === obj.__proto__toString == Object.prototype.toString
|
|
||||||
```
|
|
||||||
|
|
||||||
Please note that there is no additional `[[Prototype]]` in the chain above `Object.prototype`:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
alert(Object.prototype.__proto__); // null
|
|
||||||
```
|
|
||||||
|
|
||||||
## Getting all properties
|
|
||||||
|
|
||||||
There are many ways to get keys/values from an object:
|
|
||||||
|
|
||||||
- [Object.getOwnPropertyNames(obj)](mdn:js/Object/getOwnPropertyNames) -- returns an array of all own string property names.
|
|
||||||
- [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) -- returns an array of all own symbolic property names.
|
|
||||||
- [Object.keys(obj)](mdn:js/Object/keys) / [Object.values(obj)](mdn:js/Object/values) / [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of enumerable own string property names/values/key-value pairs.
|
|
||||||
|
|
||||||
All of them operate on the object itself. But `for..in` loop is different: it also gives inherited properties.
|
|
||||||
|
|
||||||
For instance:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
eats: true
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
jumps: true,
|
|
||||||
__proto__: animal
|
|
||||||
};
|
|
||||||
|
|
||||||
*!*
|
|
||||||
// only own keys
|
|
||||||
alert(Object.keys(rabbit)); // jumps
|
|
||||||
*/!*
|
|
||||||
|
|
||||||
*!*
|
|
||||||
// inherited keys too
|
|
||||||
for(let prop in rabbit) alert(prop); // jumps, then eats
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
If we want to differ inherited properties, there's a built-in method [obj.hasOwnProperty(key)](mdn:js/Object/hasOwnProperty): it returns `true` if `obj` has its own (not inherited) property named `key`.
|
|
||||||
|
|
||||||
So we can filter out inherited properties (or do something else with them):
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
eats: true
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
jumps: true,
|
|
||||||
__proto__: animal
|
|
||||||
};
|
|
||||||
|
|
||||||
for(let prop in rabbit) {
|
|
||||||
let isOwn = rabbit.hasOwnProperty(prop);
|
|
||||||
alert(`${prop}: ${isOwn}`); // jumps:true, then eats:false
|
|
||||||
}
|
|
||||||
```
|
|
||||||
Here we have the following inheritance chain: `rabbit`, then `animal`, then `Object.prototype` (because `animal` is a literal object `{...}`, so it's by default), and then `null` above it:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
So when `rabbit.hasOwnProperty` is called, the method `hasOwnProperty` is taken from `Object.prototype`. Why `hasOwnProperty` itself does not appear in `for..in` loop? The answer is simple: it's not enumerable just like all other properties of `Object.prototype`.
|
|
||||||
|
|
||||||
As a take-away, let's remember that if we want inherited properties -- we should use `for..in`, and otherwise we can use other iteration methods or add the `hasOwnProperty` check.
|
|
||||||
|
|
||||||
## Prototype setters and getters
|
|
||||||
|
|
||||||
There are also other ways to get/set a prototype, besides those that we already know:
|
There are also other ways to get/set a prototype, besides those that we already know:
|
||||||
|
|
||||||
|
@ -108,6 +7,7 @@ There are also other ways to get/set a prototype, besides those that we already
|
||||||
- [Object.getPrototypeOf(obj)](mdn:js/Object.getPrototypeOf) -- returns the `[[Prototype]]` of `obj`.
|
- [Object.getPrototypeOf(obj)](mdn:js/Object.getPrototypeOf) -- returns the `[[Prototype]]` of `obj`.
|
||||||
- [Object.setPrototypeOf(obj, proto)](mdn:js/Object.setPrototypeOf) -- sets the `[[Prototype]]` of `obj` to `proto`.
|
- [Object.setPrototypeOf(obj, proto)](mdn:js/Object.setPrototypeOf) -- sets the `[[Prototype]]` of `obj` to `proto`.
|
||||||
|
|
||||||
|
[cut]
|
||||||
|
|
||||||
For instance:
|
For instance:
|
||||||
|
|
||||||
|
@ -236,13 +136,86 @@ chineseDictionary.bye = "zai jian";
|
||||||
alert(Object.keys(chineseDictionary)); // hello,bye
|
alert(Object.keys(chineseDictionary)); // hello,bye
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Getting all properties
|
||||||
|
|
||||||
## Summary
|
There are many ways to get keys/values from an object.
|
||||||
|
|
||||||
|
We already know these ones:
|
||||||
|
|
||||||
|
- [Object.keys(obj)](mdn:js/Object/keys) / [Object.values(obj)](mdn:js/Object/values) / [Object.entries(obj)](mdn:js/Object/entries) -- returns an array of enumerable own string property names/values/key-value pairs.
|
||||||
|
|
||||||
|
These methods only list *enumerable* properties, and those that have *strings as keys*.
|
||||||
|
|
||||||
|
If we want symbolic properties:
|
||||||
|
|
||||||
|
- [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) -- returns an array of all own symbolic property names.
|
||||||
|
|
||||||
|
If we want non-enumerable properties:
|
||||||
|
|
||||||
|
- [Object.getOwnPropertyNames(obj)](mdn:js/Object/getOwnPropertyNames) -- returns an array of all own string property names.
|
||||||
|
|
||||||
|
If we want *everything*:
|
||||||
|
|
||||||
|
- [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) -- returns an array of all own property names.
|
||||||
|
|
||||||
|
All of them operate on the object itself. Properties from the prototype are not listed.
|
||||||
|
|
||||||
|
But `for..in` loop is different: it also gives inherited properties.
|
||||||
|
|
||||||
|
For instance:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
let animal = {
|
||||||
|
eats: true
|
||||||
|
};
|
||||||
|
|
||||||
|
let rabbit = {
|
||||||
|
jumps: true,
|
||||||
|
__proto__: animal
|
||||||
|
};
|
||||||
|
|
||||||
|
*!*
|
||||||
|
// only own keys
|
||||||
|
alert(Object.keys(rabbit)); // jumps
|
||||||
|
*/!*
|
||||||
|
|
||||||
|
*!*
|
||||||
|
// inherited keys too
|
||||||
|
for(let prop in rabbit) alert(prop); // jumps, then eats
|
||||||
|
*/!*
|
||||||
|
```
|
||||||
|
|
||||||
|
If we want to distinguish inherited properties, there's a built-in method [obj.hasOwnProperty(key)](mdn:js/Object/hasOwnProperty): it returns `true` if `obj` has its own (not inherited) property named `key`.
|
||||||
|
|
||||||
|
So we can filter out inherited properties (or do something else with them):
|
||||||
|
|
||||||
|
```js run
|
||||||
|
let animal = {
|
||||||
|
eats: true
|
||||||
|
};
|
||||||
|
|
||||||
|
let rabbit = {
|
||||||
|
jumps: true,
|
||||||
|
__proto__: animal
|
||||||
|
};
|
||||||
|
|
||||||
|
for(let prop in rabbit) {
|
||||||
|
let isOwn = rabbit.hasOwnProperty(prop);
|
||||||
|
alert(`${prop}: ${isOwn}`); // jumps:true, then eats:false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Here we have the following inheritance chain: `rabbit`, then `animal`, then `Object.prototype` (because `animal` is a literal object `{...}`, so it's by default), and then `null` above it:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
So when `rabbit.hasOwnProperty` is called, the method `hasOwnProperty` is taken from `Object.prototype`. Why `hasOwnProperty` itself does not appear in `for..in` loop? The answer is simple: it's not enumerable just like all other properties of `Object.prototype`.
|
||||||
|
|
||||||
|
As a take-away, let's remember that if we want inherited properties -- we should use `for..in`, and otherwise we can use other iteration methods or add the `hasOwnProperty` check.
|
||||||
|
|
||||||
|
## Summary [todo]
|
||||||
|
|
||||||
The `"prototype"` property of constructor functions is essential for Javascript built-in methods.
|
The `"prototype"` property of constructor functions is essential for Javascript built-in methods.
|
||||||
|
|
||||||
In this chapter we saw how it works for objects:
|
In this chapter we saw how it works for objects:
|
||||||
|
|
||||||
-
|
|
||||||
|
|
||||||
In the next chapter we'll see the bigger picture: how other built-ins rely on it to inherit from each other.
|
In the next chapter we'll see the bigger picture: how other built-ins rely on it to inherit from each other.
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 50 KiB After Width: | Height: | Size: 50 KiB |
|
@ -1,89 +0,0 @@
|
||||||
|
|
||||||
# The "constructor" property
|
|
||||||
|
|
||||||
[todo make me more interesting]
|
|
||||||
Every function by default already has the `"prototype"` property.
|
|
||||||
|
|
||||||
It's an object of this form:
|
|
||||||
|
|
||||||
```js
|
|
||||||
function Rabbit() {}
|
|
||||||
|
|
||||||
Rabbit.prototype = {
|
|
||||||
constructor: Rabbit
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
Here, `Rabbit.prototype` is assigned manually, but the same object is its value by default.
|
|
||||||
|
|
||||||
We can check it:
|
|
||||||
|
|
||||||
```js
|
|
||||||
function Rabbit() {}
|
|
||||||
// Rabbit.prototype = { constructor: Rabbit }
|
|
||||||
|
|
||||||
alert( Rabbit.prototype.constructor == Rabbit ); // true
|
|
||||||
```
|
|
||||||
|
|
||||||
Here's the picture:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Naturally, the `"constructor"` property becomes available to all rabbits through the `[[Prototype]]`:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
function Rabbit() {}
|
|
||||||
|
|
||||||
let rabbit = new Rabbit();
|
|
||||||
|
|
||||||
alert(rabbit.constructor == Rabbit); // true
|
|
||||||
```
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
We can use it to create a new object using the same constructor as the existing one:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
function Rabbit(name) {
|
|
||||||
this.name = name;
|
|
||||||
alert(name);
|
|
||||||
}
|
|
||||||
|
|
||||||
let rabbit = new Rabbit("White Rabbit");
|
|
||||||
|
|
||||||
let rabbit2 = new rabbit.constructor("Black Rabbit");
|
|
||||||
```
|
|
||||||
|
|
||||||
That may come in handy when we have an object, but don't know which constructor was used for it (e.g. it comes from a 3rd party library), and we need to create the same.
|
|
||||||
|
|
||||||
Probably the most important thing about `"constructor"` is that...
|
|
||||||
|
|
||||||
**JavaScript itself does not use the `"constructor"` property at all.**
|
|
||||||
|
|
||||||
Yes, it exists in the default `"prototype"` for functions, but that's literally all about it. No language function relies on it and nothing controls its validity.
|
|
||||||
|
|
||||||
It is created automatically, but what happens with it later -- is totally on us.
|
|
||||||
|
|
||||||
In particular, if we assign our own `Rabbit.prototype = { jumps: true }`, then there will be no `"constructor"` in it any more.
|
|
||||||
|
|
||||||
Such assignment won't break native methods or syntax, because nothing in the language uses the `"constructor"` property. But we may want to keep `"constructor"` for convenience or just in case, by adding properties to the default `"prototype"` instead of overwriting it as a whole:
|
|
||||||
|
|
||||||
```js
|
|
||||||
function Rabbit() {}
|
|
||||||
|
|
||||||
// Not overwrite Rabbit.prototype totally
|
|
||||||
// just add to it
|
|
||||||
Rabbit.prototype.jumps = true
|
|
||||||
// the default Rabbit.prototype.constructor is preserved
|
|
||||||
```
|
|
||||||
|
|
||||||
Or, alternatively, recreate it manually:
|
|
||||||
|
|
||||||
```js
|
|
||||||
Rabbit.prototype = {
|
|
||||||
jumps: true,
|
|
||||||
*!*
|
|
||||||
constructor: Rabbit
|
|
||||||
*/!*
|
|
||||||
};
|
|
||||||
```
|
|
Before Width: | Height: | Size: 9.8 KiB |
Before Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 44 KiB |
Before Width: | Height: | Size: 105 KiB |
Before Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 4 KiB |
Before Width: | Height: | Size: 9.1 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 35 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 34 KiB |
Before Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 50 KiB |
Before Width: | Height: | Size: 14 KiB |
Before Width: | Height: | Size: 34 KiB |
|
@ -0,0 +1,46 @@
|
||||||
|
Here's the line with the error:
|
||||||
|
|
||||||
|
```js
|
||||||
|
Rabbit.prototype = Animal.prototype;
|
||||||
|
```
|
||||||
|
|
||||||
|
Here `Rabbit.prototype` and `Animal.prototype` become the same object. So methods of both classes become mixed in that object.
|
||||||
|
|
||||||
|
As a result, `Rabbit.prototype.walk` overwrites `Animal.prototype.walk`, so all animals start to bounce:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
function Animal(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Animal.prototype.walk = function() {
|
||||||
|
alert(this.name + ' walks');
|
||||||
|
};
|
||||||
|
|
||||||
|
function Rabbit(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
*!*
|
||||||
|
Rabbit.prototype = Animal.prototype;
|
||||||
|
*/!*
|
||||||
|
|
||||||
|
Rabbit.prototype.walk = function() {
|
||||||
|
alert(this.name + " bounces!");
|
||||||
|
};
|
||||||
|
|
||||||
|
*!*
|
||||||
|
let animal = new Animal("pig");
|
||||||
|
animal.walk(); // pig bounces!
|
||||||
|
*/!*
|
||||||
|
```
|
||||||
|
|
||||||
|
The correct variant would be:
|
||||||
|
|
||||||
|
```js
|
||||||
|
Rabbit.prototype.__proto__ = Animal.prototype;
|
||||||
|
// or like this:
|
||||||
|
Rabbit.prototype = Object.create(Animal.prototype);
|
||||||
|
```
|
||||||
|
|
||||||
|
That makes prototypes separate, each of them stores methods of the corresponding class, but `Rabbit.prototype` inherits from `Animal.prototype`.
|
|
@ -0,0 +1,29 @@
|
||||||
|
importance: 5
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# An error in the inheritance
|
||||||
|
|
||||||
|
Find an error in the prototypal inheritance below.
|
||||||
|
|
||||||
|
What's wrong? What are consequences going to be?
|
||||||
|
|
||||||
|
```js
|
||||||
|
function Animal(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Animal.prototype.walk = function() {
|
||||||
|
alert(this.name + ' walks');
|
||||||
|
};
|
||||||
|
|
||||||
|
function Rabbit(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Rabbit.prototype = Animal.prototype;
|
||||||
|
|
||||||
|
Rabbit.prototype.walk = function() {
|
||||||
|
alert(this.name + " bounces!");
|
||||||
|
};
|
||||||
|
```
|
|
@ -0,0 +1 @@
|
||||||
|
Please note that properties that were internal in functional style (`template`, `timer`) and the internal method `render` are marked private with the underscore `_`.
|
|
@ -0,0 +1,32 @@
|
||||||
|
function Clock({ template }) {
|
||||||
|
this._template = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
Clock.prototype._render = function() {
|
||||||
|
let date = new Date();
|
||||||
|
|
||||||
|
let hours = date.getHours();
|
||||||
|
if (hours < 10) hours = '0' + hours;
|
||||||
|
|
||||||
|
let mins = date.getMinutes();
|
||||||
|
if (mins < 10) min = '0' + mins;
|
||||||
|
|
||||||
|
let secs = date.getSeconds();
|
||||||
|
if (secs < 10) secs = '0' + secs;
|
||||||
|
|
||||||
|
let output = this._template
|
||||||
|
.replace('h', hours)
|
||||||
|
.replace('m', mins)
|
||||||
|
.replace('s', secs);
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
};
|
||||||
|
|
||||||
|
Clock.prototype.stop = function() {
|
||||||
|
clearInterval(this._timer);
|
||||||
|
};
|
||||||
|
|
||||||
|
Clock.prototype.start = function() {
|
||||||
|
this._render();
|
||||||
|
this._timer = setInterval(() => this._render(), 1000);
|
||||||
|
};
|
|
@ -2,7 +2,7 @@
|
||||||
<html>
|
<html>
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<title>Часики в консоли</title>
|
<title>Console clock</title>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
|
@ -10,12 +10,9 @@
|
||||||
|
|
||||||
<script src="clock.js"></script>
|
<script src="clock.js"></script>
|
||||||
<script>
|
<script>
|
||||||
var clock = new Clock({
|
let clock = new Clock({template: 'h:m:s'});
|
||||||
template: 'h:m:s'
|
|
||||||
});
|
|
||||||
clock.start();
|
clock.start();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
</html>
|
||||||
</html>
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
function Clock({ template }) {
|
||||||
|
|
||||||
|
let timer;
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
let date = new Date();
|
||||||
|
|
||||||
|
let hours = date.getHours();
|
||||||
|
if (hours < 10) hours = '0' + hours;
|
||||||
|
|
||||||
|
let mins = date.getMinutes();
|
||||||
|
if (mins < 10) min = '0' + mins;
|
||||||
|
|
||||||
|
let secs = date.getSeconds();
|
||||||
|
if (secs < 10) secs = '0' + secs;
|
||||||
|
|
||||||
|
let output = template
|
||||||
|
.replace('h', hours)
|
||||||
|
.replace('m', mins)
|
||||||
|
.replace('s', secs);
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.stop = function() {
|
||||||
|
clearInterval(timer);
|
||||||
|
};
|
||||||
|
|
||||||
|
this.start = function() {
|
||||||
|
render();
|
||||||
|
timer = setInterval(render, 1000);
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
|
@ -2,7 +2,7 @@
|
||||||
<html>
|
<html>
|
||||||
|
|
||||||
<head>
|
<head>
|
||||||
<title>Часики в консоли</title>
|
<title>Console clock</title>
|
||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
|
@ -10,12 +10,9 @@
|
||||||
|
|
||||||
<script src="clock.js"></script>
|
<script src="clock.js"></script>
|
||||||
<script>
|
<script>
|
||||||
var clock = new Clock({
|
let clock = new Clock({template: 'h:m:s'});
|
||||||
template: 'h:m:s'
|
|
||||||
});
|
|
||||||
clock.start();
|
clock.start();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
</html>
|
||||||
</html>
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
importance: 5
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Rewrite to prototypes
|
||||||
|
|
||||||
|
The `Clock` class is written in functional style. Rewrite it using prototypes.
|
||||||
|
|
||||||
|
P.S. The clock ticks in the console, open it to see.
|
|
@ -31,41 +31,25 @@ user.sayHi(); // John
|
||||||
|
|
||||||
It follows all parts of the definition:
|
It follows all parts of the definition:
|
||||||
|
|
||||||
1. It is a program-code-template for creating objects (callable with `new`).
|
1. It is a "program-code-template" for creating objects (callable with `new`).
|
||||||
2. It provides initial values for state (`name` from parameters).
|
2. It provides initial values for the state (`name` from parameters).
|
||||||
3. It provides methods (`sayHi`).
|
3. It provides methods (`sayHi`).
|
||||||
|
|
||||||
This is called *functional class pattern*. It is rarely used, because prototypes are generally better.
|
This is called *functional class pattern*.
|
||||||
|
|
||||||
Here's the same class rewritten using prototypes:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
function User(name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
User.prototype.sayHi = function() {
|
|
||||||
alert(this.name);
|
|
||||||
};
|
|
||||||
|
|
||||||
let user = new User("John");
|
|
||||||
user.sayHi(); // John
|
|
||||||
```
|
|
||||||
|
|
||||||
Now the method `sayHi` is shared between all users through prototype. That's more memory-efficient as putting a copy of it into every object like the functional pattern does. Prototype-based classes are also more convenient for inheritance. As we've seen, that's what the language itself uses, and we'll be using them further on.
|
|
||||||
|
|
||||||
### Internal properties and methods
|
|
||||||
|
|
||||||
In the functional class pattern, variables and functions inside `User`, that are not assigned to `this`, are visible from inside, but not accessible by the outer code.
|
In the functional class pattern, variables and functions inside `User`, that are not assigned to `this`, are visible from inside, but not accessible by the outer code.
|
||||||
|
|
||||||
Here's a bigger example:
|
So we can easily add internal functions and variables, like `calcAge()` here:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
function User(name, birthday) {
|
function User(name, birthday) {
|
||||||
|
|
||||||
|
*!*
|
||||||
|
// only visible from other methods inside User
|
||||||
function calcAge() {
|
function calcAge() {
|
||||||
new Date().getFullYear() - birthday.getFullYear();
|
new Date().getFullYear() - birthday.getFullYear();
|
||||||
}
|
}
|
||||||
|
*/!*
|
||||||
|
|
||||||
this.sayHi = function() {
|
this.sayHi = function() {
|
||||||
alert(name + ', age:' + calcAge());
|
alert(name + ', age:' + calcAge());
|
||||||
|
@ -78,13 +62,15 @@ user.sayHi(); // John
|
||||||
|
|
||||||
Variables `name`, `birthday` and the function `calcAge()` are internal, *private* to the object. They are only visible from inside of it. The external code that creates the `user` only can see a *public* method `sayHi`.
|
Variables `name`, `birthday` and the function `calcAge()` are internal, *private* to the object. They are only visible from inside of it. The external code that creates the `user` only can see a *public* method `sayHi`.
|
||||||
|
|
||||||
In short, functional classes provide a shared outer lexical environment for private variables and methods.
|
In works, because functional classes provide a shared lexical environment (of `User`) for private variables and methods.
|
||||||
|
|
||||||
Prototype-bases classes do not have it. As we can see, methods are created outside of the constructor, in the prototype. And per-object data like `name` is stored in object properties. So, technically they are all available for external code.
|
## Prototype-based classes
|
||||||
|
|
||||||
But there is a widely known agreement that internal properties are prepended with an underscore `"_"`.
|
Functional class pattern is rarely used, because prototypes are generally better.
|
||||||
|
|
||||||
Like this:
|
Soon you'll see why.
|
||||||
|
|
||||||
|
Here's the same class rewritten using prototypes:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
function User(name, birthday) {
|
function User(name, birthday) {
|
||||||
|
@ -108,17 +94,43 @@ let user = new User("John", new Date(2000,0,1));
|
||||||
user.sayHi(); // John
|
user.sayHi(); // John
|
||||||
```
|
```
|
||||||
|
|
||||||
Technically, that changes nothing. But most developers recognize the meaning of `"_"` and try not to touch prefixed properties and methods in external code.
|
- The constructor `User` only initializes the current object state.
|
||||||
|
- Methods reside in `User.prototype`.
|
||||||
|
|
||||||
## Prototype-based classes
|
Here methods are technically not inside `function User`, so they do not share a common lexical environment.
|
||||||
|
|
||||||
Prototype-based classes are structured like this:
|
So, there is a widely known agreement that internal properties and methods are prepended with an underscore `"_"`. Like `_name` or `_calcAge()`. Technically, that's just an agreement, the outer code still can access them. But most developers recognize the meaning of `"_"` and try not to touch prefixed properties and methods in the external code.
|
||||||
|
|
||||||

|
We already can see benefits over the functional pattern:
|
||||||
|
|
||||||
The code example:
|
- In the functional pattern, each object has its own copy of methods like `this.sayHi = function() {...}`.
|
||||||
|
- In the prototypal pattern, there's a common `User.prototype` shared between all user objects.
|
||||||
|
|
||||||
```js run
|
So the prototypal pattern is more memory-efficient.
|
||||||
|
|
||||||
|
...But not only that. Prototypes allow us to setup the inheritance, precisely the same way as built-in Javascript constructors do. Functional pattern allows to wrap a function into another function, and kind-of emulate inheritance this way, but that's far less effective, so here we won't go into details to save our time.
|
||||||
|
|
||||||
|
## Prototype-based inheritance for classes
|
||||||
|
|
||||||
|
Let's say we have two prototype-based classes:
|
||||||
|
|
||||||
|
```js
|
||||||
|
function Rabbit(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Rabbit.prototype.jump = function() {
|
||||||
|
alert(this.name + ' jumps!');
|
||||||
|
};
|
||||||
|
|
||||||
|
let rabbit = new Rabbit("My rabbit");
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
And:
|
||||||
|
|
||||||
|
```js
|
||||||
function Animal(name) {
|
function Animal(name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
@ -127,31 +139,60 @@ Animal.prototype.eat = function() {
|
||||||
alert(this.name + ' eats.');
|
alert(this.name + ' eats.');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let animal = new Animal("My animal");
|
||||||
|
```
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
Right now they are fully independent.
|
||||||
|
|
||||||
|
But naturally we'd like `Rabbit` to inherit from `Animal`. In other words, rabbits should be based on animals, and extend them with methods of their own.
|
||||||
|
|
||||||
|
What does it mean in the language on prototypes?
|
||||||
|
|
||||||
|
Right now `rabbit` objects have access to `Rabbit.prototype`. We should add `Animal.prototype` to it. So the chain would be `rabbit -> Rabbit.prototype -> Animal.prototype`.
|
||||||
|
|
||||||
|
Like this:
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
The code example:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
// Same Animal as before
|
||||||
|
function Animal(name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
Animal.prototype.eat = function() {
|
||||||
|
alert(this.name + ' eats.');
|
||||||
|
};
|
||||||
|
|
||||||
|
// Same Rabbit as before
|
||||||
function Rabbit(name) {
|
function Rabbit(name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
|
||||||
*!*
|
|
||||||
// inherit methods
|
|
||||||
Object.setPrototypeOf(Rabbit.prototype, Animal.prototype); // (*)
|
|
||||||
*/!*
|
|
||||||
|
|
||||||
Rabbit.prototype.jump = function() {
|
Rabbit.prototype.jump = function() {
|
||||||
alert(this.name + ' jumps!');
|
alert(this.name + ' jumps!');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
*!*
|
||||||
|
// setup the inheritance chain
|
||||||
|
Rabbit.prototype.__proto__ = Animal.prototype; // (*)
|
||||||
|
*/!*
|
||||||
|
|
||||||
let rabbit = new Rabbit("White Rabbit")
|
let rabbit = new Rabbit("White Rabbit")
|
||||||
rabbit.eat();
|
rabbit.eat();
|
||||||
rabbit.jump();
|
rabbit.jump();
|
||||||
```
|
```
|
||||||
|
|
||||||
Here the line `(*)` sets up the prototype chain. So that `rabbit` first searches methods in `Rabbit.prototype`, then `Animal.prototype`. And then `Object.prototype`, because `Animal.prototype` is a regular plain object, so it inherits from it, that's not painted for brevity.
|
The line `(*)` sets up the prototype chain. So that `rabbit` first searches methods in `Rabbit.prototype`, then `Animal.prototype`. And then, just for completeness, the search may continue in `Object.prototype`, because `Animal.prototype` is a regular plain object, so it inherits from it. But that's not painted for brevity.
|
||||||
|
|
||||||
The structure of exactly that code piece is:
|
Here's what the code does:
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
## Summary [todo]
|
||||||
|
|
||||||
## Todo
|
One of problems is lots of words, for every method we write "Rabbit.prototype.method = ..." Classes syntax is sugar fixes that.
|
||||||
|
|
||||||
call parent method (overrides)
|
|
||||||
|
|
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 58 KiB |
After Width: | Height: | Size: 16 KiB |
After Width: | Height: | Size: 38 KiB |
After Width: | Height: | Size: 15 KiB |
After Width: | Height: | Size: 38 KiB |
|
@ -0,0 +1,34 @@
|
||||||
|
class Clock {
|
||||||
|
constructor({ template }) {
|
||||||
|
this._template = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
_render() {
|
||||||
|
let date = new Date();
|
||||||
|
|
||||||
|
let hours = date.getHours();
|
||||||
|
if (hours < 10) hours = '0' + hours;
|
||||||
|
|
||||||
|
let mins = date.getMinutes();
|
||||||
|
if (mins < 10) min = '0' + mins;
|
||||||
|
|
||||||
|
let secs = date.getSeconds();
|
||||||
|
if (secs < 10) secs = '0' + secs;
|
||||||
|
|
||||||
|
let output = this._template
|
||||||
|
.replace('h', hours)
|
||||||
|
.replace('m', mins)
|
||||||
|
.replace('s', secs);
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
clearInterval(this._timer);
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
this._render();
|
||||||
|
this._timer = setInterval(() => this._render(), 1000);
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,18 @@
|
||||||
|
<!DOCTYPE HTML>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<title>Console clock</title>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<script src="clock.js"></script>
|
||||||
|
<script>
|
||||||
|
let clock = new Clock({template: 'h:m:s'});
|
||||||
|
clock.start();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,34 @@
|
||||||
|
|
||||||
|
|
||||||
|
function Clock({ template }) {
|
||||||
|
this._template = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
Clock.prototype._render = function() {
|
||||||
|
let date = new Date();
|
||||||
|
|
||||||
|
let hours = date.getHours();
|
||||||
|
if (hours < 10) hours = '0' + hours;
|
||||||
|
|
||||||
|
let mins = date.getMinutes();
|
||||||
|
if (mins < 10) min = '0' + mins;
|
||||||
|
|
||||||
|
let secs = date.getSeconds();
|
||||||
|
if (secs < 10) secs = '0' + secs;
|
||||||
|
|
||||||
|
let output = this._template
|
||||||
|
.replace('h', hours)
|
||||||
|
.replace('m', mins)
|
||||||
|
.replace('s', secs);
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
};
|
||||||
|
|
||||||
|
Clock.prototype.stop = function() {
|
||||||
|
clearInterval(this._timer);
|
||||||
|
};
|
||||||
|
|
||||||
|
Clock.prototype.start = function() {
|
||||||
|
this._render();
|
||||||
|
this._timer = setInterval(() => this._render(), 1000);
|
||||||
|
};
|
|
@ -0,0 +1,18 @@
|
||||||
|
<!DOCTYPE HTML>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<title>Console clock</title>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<script src="clock.js"></script>
|
||||||
|
<script>
|
||||||
|
let clock = new Clock({template: 'h:m:s'});
|
||||||
|
clock.start();
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -0,0 +1,9 @@
|
||||||
|
importance: 5
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Rewrite to class
|
||||||
|
|
||||||
|
Rewrite the `Clock` class from prototypes to the modern "class" syntax.
|
||||||
|
|
||||||
|
P.S. The clock ticks in the console, open it to see.
|
BIN
1-js/9-object-inheritance/09-class/animal-rabbit-extends.png
Normal file
After Width: | Height: | Size: 30 KiB |
BIN
1-js/9-object-inheritance/09-class/animal-rabbit-extends@2x.png
Normal file
After Width: | Height: | Size: 73 KiB |
|
@ -1,21 +1,17 @@
|
||||||
|
|
||||||
# Classes
|
# Classes
|
||||||
|
|
||||||
The "class" construct allows to define prototype-based classes with a much more comfortable syntax than before.
|
The "class" construct allows to define prototype-based classes with a clean, nice-looking syntax.
|
||||||
|
|
||||||
But more than that -- there are also other inheritance-related features baked in.
|
|
||||||
|
|
||||||
[cut]
|
[cut]
|
||||||
|
|
||||||
## The "class" syntax
|
## The "class" syntax
|
||||||
|
|
||||||
<!--The class syntax is versatile, so we'll first see the overall picture and then explore it by examples.-->
|
The `class` syntax is versatile, so we'll start from a simple example first.
|
||||||
|
|
||||||
The class syntax is versatile, so we'll start from a simple class, and then build on top of it.
|
Here's a prototype-based class `User`:
|
||||||
|
|
||||||
A prototype-based class `User`:
|
```js run
|
||||||
|
|
||||||
```js
|
|
||||||
function User(name) {
|
function User(name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
@ -23,13 +19,16 @@ function User(name) {
|
||||||
User.prototype.sayHi = function() {
|
User.prototype.sayHi = function() {
|
||||||
alert(this.name);
|
alert(this.name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let user = new User("John");
|
||||||
|
user.sayHi();
|
||||||
```
|
```
|
||||||
|
|
||||||
Can be rewritten as:
|
...And that's the same using `class` syntax:
|
||||||
|
|
||||||
```js
|
```js run
|
||||||
class User {
|
class User {
|
||||||
|
|
||||||
constructor(name) {
|
constructor(name) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
}
|
}
|
||||||
|
@ -39,15 +38,19 @@ class User {
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let user = new User("John");
|
||||||
|
user.sayHi();
|
||||||
```
|
```
|
||||||
|
|
||||||
The `"class"` construct is tricky from the beginning. We may think that it defines a new lanuage-level entity, but no!
|
It's easy to see that the two examples are alike. So, what exactly the `class` does? We may think that it defines a new language-level entity, but that would be wrong.
|
||||||
|
|
||||||
The resulting variable `User` is actually a function labelled as a `"constructor"`. The value of `User.prototype` is an object with methods listed in the definition. Here it includes `sayHi` and, well, the reference to `constructor` also.
|
The `class User {...}` here actually does two things:
|
||||||
|
|
||||||

|
1. Declares a variable `User` that references the function named `"constructor"`.
|
||||||
|
2. Puts into `User.prototype` methods listed in the definition. Here it includes `sayHi` and the `constructor`.
|
||||||
|
|
||||||
Here, let's check it:
|
Here's some code to demonstrate that:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
class User {
|
class User {
|
||||||
|
@ -55,29 +58,60 @@ class User {
|
||||||
sayHi() { alert(this.name); }
|
sayHi() { alert(this.name); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// proof: User is the same as constructor
|
*!*
|
||||||
|
// proof: User is the "constructor" function
|
||||||
|
*/!*
|
||||||
alert(User == User.prototype.constructor); // true
|
alert(User == User.prototype.constructor); // true
|
||||||
|
|
||||||
// And there are two methods in its "prototype"
|
*!*
|
||||||
|
// proof: there are two methods in its "prototype"
|
||||||
|
*/!*
|
||||||
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi
|
alert(Object.getOwnPropertyNames(User.prototype)); // constructor, sayHi
|
||||||
|
|
||||||
// The usage is same:
|
|
||||||
let user = new User("John");
|
|
||||||
user.sayHi(); // John
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The class constructor function has two special features:
|
Here's the illustration of `class User`:
|
||||||
|
|
||||||
- It can't be called without `new`.
|

|
||||||
- If we output it like `alert(User)`, some engines show `"class User..."`, while others show `"function User..."`. Please don't be confused: the string representation may vary, but that doesn't affect anything.
|
|
||||||
|
|
||||||
Please note that no code statements and `property:value` assignments are allowed inside `class`. There may be only methods (without a comma between them) and getters/setters.
|
So `class` is a special syntax to define the constructor with prototype methods.
|
||||||
|
|
||||||
Here we use a getter/setter pair for `name` to make sure that it is valid:
|
...But not only that. There are minor tweaks here and there to ensure the right usage.
|
||||||
|
|
||||||
|
For instance, the `constructor` function can't be called without `new`:
|
||||||
|
```js run
|
||||||
|
class User {
|
||||||
|
constructor() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
alert(typeof User); // function
|
||||||
|
User(); // Error: Class constructor User cannot be invoked without 'new'
|
||||||
|
```
|
||||||
|
|
||||||
|
```smart header="Outputting a class"
|
||||||
|
If we output it like `alert(User)`, some engines show `"class User..."`, while others show `"function User..."`.
|
||||||
|
|
||||||
|
Please don't be confused: the string representation may vary, but that's still a function, there is no separate "class" entity in Javascript language.
|
||||||
|
```
|
||||||
|
|
||||||
|
```smart header="Class methods are non-enumerable"
|
||||||
|
Class definition sets `enumerable` flag to `false` for all methods in the `"prototype"`. That's good, because if we `for..in` over an object, we usually don't want its class methods.
|
||||||
|
```
|
||||||
|
|
||||||
|
```smart header="What if there's no constructor?"
|
||||||
|
If there's no `constructor` in the `class` construct, then an empty function is generated, same as if write `constructor() {}`.
|
||||||
|
```
|
||||||
|
|
||||||
|
```smart header="Classes always `use strict`"
|
||||||
|
All code inside the class construct is automatically in the strict mode.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Getters/setters
|
||||||
|
|
||||||
|
Classes may also include getters/setters. Here's an example with `user.name` implemented using them:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
class User {
|
class User {
|
||||||
|
|
||||||
constructor(name) {
|
constructor(name) {
|
||||||
// invokes the setter
|
// invokes the setter
|
||||||
this.name = name;
|
this.name = name;
|
||||||
|
@ -93,7 +127,8 @@ class User {
|
||||||
set name(value) {
|
set name(value) {
|
||||||
*/!*
|
*/!*
|
||||||
if (value.length < 4) {
|
if (value.length < 4) {
|
||||||
throw new Error("Name too short.");
|
alert("Name too short.");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
this._name = value;
|
this._name = value;
|
||||||
}
|
}
|
||||||
|
@ -103,44 +138,66 @@ class User {
|
||||||
let user = new User("John");
|
let user = new User("John");
|
||||||
alert(user.name); // John
|
alert(user.name); // John
|
||||||
|
|
||||||
user = new User(""); // Error: name too short
|
user = new User(""); // Name too short.
|
||||||
```
|
```
|
||||||
|
|
||||||
```smart header="Class methods are non-enumerable"
|
### Only methods
|
||||||
Class definition sets `enumerable` flag to `false` for all methods in the `"prototype"`. That's good, because if we `for..in` over an object, we usually don't want its methods.
|
|
||||||
|
Unlike object literals, no `property:value` assignments are allowed inside `class`. There may be only methods (without a comma between them) and getters/setters.
|
||||||
|
|
||||||
|
The idea is that everything inside `class` goes to the prototype. And the prototype should store methods only, which are shared between objects. The data describing a concrete object state should reside in individual objects.
|
||||||
|
|
||||||
|
If we really insist on putting a non-function value into the prototype, then `class` can't help here. We can alter `prototype` manually though, like this:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
class User { }
|
||||||
|
|
||||||
|
User.prototype.test = 5;
|
||||||
|
|
||||||
|
alert( new User().test ); // 5
|
||||||
```
|
```
|
||||||
|
|
||||||
```smart header="What if there's no constructor?"
|
So, technically that's possible, but we should know why we're doing it.
|
||||||
If there's no `constructor` in the `class` construct, then an empty function is generated, same as `constructor() {}`. So things still work the same way.
|
|
||||||
|
An alternative here would be to use a getter:
|
||||||
|
|
||||||
|
```js run
|
||||||
|
class User {
|
||||||
|
get test() {
|
||||||
|
return 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
alert( new User().test ); // 5
|
||||||
```
|
```
|
||||||
|
|
||||||
```smart header="Classes always `use strict`"
|
From the external code, the usage is the same. But the getter variant is probably a bit slower.
|
||||||
All code inside the class construct is automatically in the strict mode.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Class Expression
|
## Class Expression
|
||||||
|
|
||||||
Just like functions, classes can be defined inside any other expression, passed around, returned from functions etc:
|
Just like functions, classes can be defined inside another expression, passed around, returned etc.
|
||||||
|
|
||||||
|
Here's a class-returning function ("class factory"):
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
function getClass() {
|
function getClass(phrase) {
|
||||||
*!*
|
*!*
|
||||||
return class {
|
return class {
|
||||||
sayHi() {
|
sayHi() {
|
||||||
alert("Hello");
|
alert(phrase);
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
*/!*
|
*/!*
|
||||||
}
|
}
|
||||||
|
|
||||||
let User = getClass();
|
let User = getClass("Hello");
|
||||||
|
|
||||||
new User().sayHi(); // Hello
|
new User().sayHi(); // Hello
|
||||||
```
|
```
|
||||||
|
|
||||||
That's normal if we recall that `class` is just a special form of constructor-and-prototype definition.
|
That's quite normal if we recall that `class` is just a special form of function-with-prototype definition.
|
||||||
|
|
||||||
Such classes also may have a name, that is visible inside that class only:
|
And, like Named Function Expressions, such classes also may have a name, that is visible inside that class only:
|
||||||
|
|
||||||
```js run
|
```js run
|
||||||
let User = class *!*MyClass*/!* {
|
let User = class *!*MyClass*/!* {
|
||||||
|
@ -149,342 +206,11 @@ let User = class *!*MyClass*/!* {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
new User().sayHi(); // works
|
new User().sayHi(); // works, shows MyClass definition
|
||||||
|
|
||||||
alert(MyClass); // error, MyClass is only visible in methods of the class
|
alert(MyClass); // error, MyClass is only visible in methods of the class
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
## Inheritance, super
|
|
||||||
|
|
||||||
To inherit from another class, we can specify `"extends"` and the parent class before the brackets `{..}`.
|
|
||||||
|
|
||||||
Here `Rabbit` inherits from `Animal`:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {
|
|
||||||
|
|
||||||
constructor(name) {
|
|
||||||
this.speed = 0;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
run(speed) {
|
|
||||||
this.speed += speed;
|
|
||||||
alert(`${this.name} runs with speed ${this.speed}.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
this.speed = 0;
|
|
||||||
alert(`${this.name} stopped.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
*!*
|
|
||||||
// Inherit from Animal
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
hide() {
|
|
||||||
alert(`${this.name} hides!`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*/!*
|
|
||||||
|
|
||||||
let rabbit = new Rabbit("White Rabbit");
|
|
||||||
|
|
||||||
rabbit.run(5); // White Rabbit runs with speed 5.
|
|
||||||
rabbit.hide(); // White Rabbit hides!
|
|
||||||
```
|
|
||||||
|
|
||||||
The `extends` keyword adds a `[[Prototype]]` reference from `Rabbit.prototype` to `Animal.prototype`, just as you expect it to be, and as we've seen before.
|
|
||||||
|
|
||||||
Now let's move forward and override a method. Naturally, if we specify our own `stop` in `Rabbit`, then the inherited one will not be called:
|
|
||||||
|
|
||||||
```js
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
stop() {
|
|
||||||
// ...this will be used for rabbit.stop()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
...But usually we don't want to fully replace a parent method, but rather to build on top of it, tweak or extend its functionality. So we do something in our method, but call the parent method before/after or in the process.
|
|
||||||
|
|
||||||
Classes provide `"super"` keyword for that.
|
|
||||||
|
|
||||||
- `super.method(...)` to call a parent method.
|
|
||||||
- `super(...)` to call a parent constructor (inside our constructor only).
|
|
||||||
|
|
||||||
For instance, let our rabbit autohide when stopped:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {
|
|
||||||
|
|
||||||
constructor(name) {
|
|
||||||
this.speed = 0;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
run(speed) {
|
|
||||||
this.speed += speed;
|
|
||||||
alert(`${this.name} runs with speed ${this.speed}.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
this.speed = 0;
|
|
||||||
alert(`${this.name} stopped.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
hide() {
|
|
||||||
alert(`${this.name} hides!`);
|
|
||||||
}
|
|
||||||
|
|
||||||
*!*
|
|
||||||
stop() {
|
|
||||||
super.stop(); // call parent stop
|
|
||||||
hide(); // and then hide
|
|
||||||
}
|
|
||||||
*/!*
|
|
||||||
}
|
|
||||||
|
|
||||||
let rabbit = new Rabbit("White Rabbit");
|
|
||||||
|
|
||||||
rabbit.run(5); // White Rabbit runs with speed 5.
|
|
||||||
rabbit.stop(); // White Rabbit stopped. White rabbit hides!
|
|
||||||
```
|
|
||||||
|
|
||||||
With constructors, it is a bit more tricky.
|
|
||||||
|
|
||||||
Let's add a constructor to `Rabbit` that specifies the ear length:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {
|
|
||||||
|
|
||||||
constructor(name) {
|
|
||||||
this.speed = 0;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
|
|
||||||
*!*
|
|
||||||
constructor(name, earLength) {
|
|
||||||
this.speed = 0;
|
|
||||||
this.name = name;
|
|
||||||
this.earLength = earLength;
|
|
||||||
}
|
|
||||||
*/!*
|
|
||||||
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
|
|
||||||
*!*
|
|
||||||
// Doesn't work!
|
|
||||||
let rabbit = new Rabbit("White Rabbit", 10); // Error
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
Wops! We've got an error, now we can't create rabbits. What went wrong?
|
|
||||||
|
|
||||||
The short answer is: "constructors in inheriting classes must call `super(...)`, and do it before using `this`".
|
|
||||||
|
|
||||||
...But why? What's going on here? Indeed, the requirement seems strange.
|
|
||||||
|
|
||||||
Of course, there's an explanation.
|
|
||||||
|
|
||||||
In JavaScript, there's a distinction between a constructor function of an inheriting class and all others. If there's an `extend`, then the constructor is labelled with an internal property `[[ConstructorKind]]:"derived"`.
|
|
||||||
|
|
||||||
- When a normal constructor runs, it creates an empty object as `this` and continues with it.
|
|
||||||
- But when a derived constructor runs, it doesn't do it. It expects the parent constructor to do this job.
|
|
||||||
|
|
||||||
So we have a choice:
|
|
||||||
|
|
||||||
- Either do not specify a constructor in the inheriting class at all. Then it will be created by default as `constructor(...args) { super(...args); }`, so `super` will be called.
|
|
||||||
- Or if we specify it, then we must call `super`, at least to create `this`. The topmost constructor in the inheritance chain is not derived, so it will make it.
|
|
||||||
|
|
||||||
The working variant:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {
|
|
||||||
|
|
||||||
constructor(name) {
|
|
||||||
this.speed = 0;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
|
|
||||||
constructor(name, earLength) {
|
|
||||||
*!*
|
|
||||||
super(name);
|
|
||||||
*/!*
|
|
||||||
this.earLength = earLength;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
|
|
||||||
*!*
|
|
||||||
// now fine
|
|
||||||
let rabbit = new Rabbit("White Rabbit", 10);
|
|
||||||
alert(rabbit.name); // White Rabbit
|
|
||||||
alert(rabbit.earLength); // 10
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
|
|
||||||
## Super: internals, [[HomeObject]]
|
|
||||||
|
|
||||||
Let's get a little deeper under the hood of `super` and learn some interesting things by the way.
|
|
||||||
|
|
||||||
First to say, from all components that we've learned till now, it's impossible for `super` to work.
|
|
||||||
|
|
||||||
Indeed, how it can work? When an object method runs, all it knows is `this`. If `super` wants to take parent methods, maybe it can just use its `[[Prototype]]`?
|
|
||||||
|
|
||||||
Let's try to do it. Without classes, using bare objects at first.
|
|
||||||
|
|
||||||
Here, `rabbit.eat()` should call `animal.eat()`.
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
name: "Animal",
|
|
||||||
eat() {
|
|
||||||
alert(this.name + " eats.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
__proto__: animal,
|
|
||||||
name: "Rabbit",
|
|
||||||
eat() {
|
|
||||||
*!*
|
|
||||||
this.__proto__.eat.call(this); // (*)
|
|
||||||
*/!*
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
rabbit.eat(); // Rabbit eats.
|
|
||||||
```
|
|
||||||
|
|
||||||
At the line `(*)` we take `eat` from the prototype (`animal`) and call it in the context of the current object. Please note that `.call(this)` is important here, because a simple `this.__proto__.eat()` would execute parent `eat` in the context of the prototype, not the current object.
|
|
||||||
|
|
||||||
And it works.
|
|
||||||
|
|
||||||
|
|
||||||
Now let's add one more object to the chain, and see how things break:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
name: "Animal",
|
|
||||||
eat() {
|
|
||||||
alert(this.name + " eats.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
__proto__: animal,
|
|
||||||
eat() {
|
|
||||||
// bounce around rabbit-style and call parent
|
|
||||||
this.__proto__.eat.call(this);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let longEar = {
|
|
||||||
__proto__: rabbit,
|
|
||||||
eat() {
|
|
||||||
// do something with long ears and call parent
|
|
||||||
this.__proto__.eat.call(this);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
*!*
|
|
||||||
longEar.eat(); // Error: Maximum call stack size exceeded
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
Doesn't work any more! If we trace `longEar.eat()` call, it becomes obvious, why:
|
|
||||||
|
|
||||||
1. Inside `longEar.eat()`, we pass the call to `rabbit.eat` giving it the same `this=longEar`.
|
|
||||||
2. Inside `rabbit.eat`, we want to pass the call even higher in the chain, but `this=longEar`, so `this.__proto__.eat` ends up being the same `rabbit.eat`!
|
|
||||||
3. ...So it calls itself in the endless loop.
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
There problem seems unsolvable, because `this` must always be the calling object itself, no matter which parent method is called. So its prototype will always be the immediate parent of the object. We can't ascend any further.
|
|
||||||
|
|
||||||
To provide the solution, JavaScript adds one more special property for functions: `[[HomeObject]]`.
|
|
||||||
|
|
||||||
**When a function is specified as a class or object method, its `[[HomeObject]]` property becomes that object.**
|
|
||||||
|
|
||||||
This actually violates the idea of "unbound" functions, because methods remember their objects. And `[[HomeObject]]` can't be changed, so this bound is forever.
|
|
||||||
|
|
||||||
But `[[HomeObject]]` is used only for calling parent methods, to resolve the prototype. So it doesn't break compatibility.
|
|
||||||
|
|
||||||
Let's see how it works:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
name: "Animal",
|
|
||||||
eat() { // [[HomeObject]] == animal
|
|
||||||
alert(this.name + " eats.");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
__proto__: animal,
|
|
||||||
name: "Rabbit",
|
|
||||||
eat() { // [[HomeObject]] == rabbit
|
|
||||||
super.eat();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let longEar = {
|
|
||||||
__proto__: rabbit,
|
|
||||||
name: "Long Ear",
|
|
||||||
eat() { // [[HomeObject]] == longEar
|
|
||||||
super.eat();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
*!*
|
|
||||||
longEar.eat(); // Long Ear eats.
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
Okay now, because `super` always resolves the parent relative to the method's `[[HomeObject]]`.
|
|
||||||
|
|
||||||
`[[HomeObject]]` works both in classes and objects. But for objects, methods must be specified exactly the given way: as `method()`, not as `"method: function()"`.
|
|
||||||
|
|
||||||
Here non-method syntax is used, so `[[HomeObject]]` property is not set and the inheritance doesn't work:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
let animal = {
|
|
||||||
eat: function() { // should be the short syntax: eat() {...}
|
|
||||||
// ...
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let rabbit = {
|
|
||||||
__proto__: animal,
|
|
||||||
eat: function() {
|
|
||||||
super.eat();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
*!*
|
|
||||||
rabbit.eat(); // Error in super, because there's no [[HomeObject]]
|
|
||||||
*/!*
|
|
||||||
```
|
|
||||||
|
|
||||||
## Static methods
|
## Static methods
|
||||||
|
|
||||||
Static methods are bound to the class function, not to its `"prototype"`.
|
Static methods are bound to the class function, not to its `"prototype"`.
|
||||||
|
@ -496,7 +222,7 @@ class User {
|
||||||
*!*
|
*!*
|
||||||
static staticMethod() {
|
static staticMethod() {
|
||||||
*/!*
|
*/!*
|
||||||
alert(this == User);
|
alert(this == User);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -505,10 +231,10 @@ User.staticMethod(); // true
|
||||||
|
|
||||||
That actually does the same as assigning it as a function property:
|
That actually does the same as assigning it as a function property:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
function User() { }
|
function User() { }
|
||||||
|
|
||||||
User.staticMethod = function() {
|
User.staticMethod = function() {
|
||||||
alert(this == User);
|
alert(this == User);
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
@ -549,7 +275,7 @@ alert( articles[0].title ); // Body
|
||||||
|
|
||||||
Here `Article.compare` stands "over" the articles, as a meants to compare them.
|
Here `Article.compare` stands "over" the articles, as a meants to compare them.
|
||||||
|
|
||||||
Another example would be a so-called "factory" method, that creates an object with specific parameters.
|
Another example would be a so-called "factory" method, that creates an object with specific parameters.
|
||||||
|
|
||||||
Like `Article.createTodays()` here:
|
Like `Article.createTodays()` here:
|
||||||
|
|
||||||
|
@ -573,81 +299,12 @@ let article = article.createTodays();
|
||||||
alert( articles.title ); // Todays digest
|
alert( articles.title ); // Todays digest
|
||||||
```
|
```
|
||||||
|
|
||||||
Now every time we need to create a todays digest, we can call `Article.createTodays()`.
|
Now every time we need to create a todays digest, we can call `Article.createTodays()`.
|
||||||
|
|
||||||
Static methods are often used in database-related classes to search/save/remove entries from the database by a query, without having them at hand.
|
Static methods are often used in database-related classes to search/save/remove entries from the database, like this:
|
||||||
|
|
||||||
|
```js
|
||||||
### Static methods and inheritance
|
// assuming Article is a special class for managing articles
|
||||||
|
// static method to remove the article:
|
||||||
The `class` syntax supports inheritance for static properties too.
|
Article.remove({id: 12345});
|
||||||
|
|
||||||
For instance:
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {
|
|
||||||
|
|
||||||
constructor(name, speed) {
|
|
||||||
this.speed = speed;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
run(speed = 0) {
|
|
||||||
this.speed += speed;
|
|
||||||
alert(`${this.name} runs with speed ${this.speed}.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
static compare(animalA, animalB) {
|
|
||||||
return animalA.speed - animalB.speed;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// Inherit from Animal
|
|
||||||
class Rabbit extends Animal {
|
|
||||||
hide() {
|
|
||||||
alert(`${this.name} hides!`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let rabbits = [
|
|
||||||
new Rabbit("White Rabbit", 10),
|
|
||||||
new Rabbit("Black Rabbit", 5)
|
|
||||||
];
|
|
||||||
|
|
||||||
rabbits.sort(Rabbit.compare);
|
|
||||||
|
|
||||||
rabbits[0].run(); // Black Rabbit runs with speed 5.
|
|
||||||
```
|
```
|
||||||
|
|
||||||
That's actually a very interesting feature, because built-in classes don't behave like that.
|
|
||||||
|
|
||||||
For instance, `Object` has `Object.defineProperty`, `Object.keys` and so on, but other objects do not inherit them.
|
|
||||||
|
|
||||||
Here's the structure for `Date` and `Object`:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Both `Object` and `Date` exist independently. Sure, `Date.prototype` inherits from `Object.prototype`, but that's all.
|
|
||||||
|
|
||||||
With classes we have one more arrow:
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
Right, `Rabbit` function now inherits from `Animal` function. And `Animal` function standartly inherits from `Function.prototype` (as other functions do).
|
|
||||||
|
|
||||||
Here, let's check:
|
|
||||||
|
|
||||||
|
|
||||||
```js run
|
|
||||||
class Animal {}
|
|
||||||
class Rabbit extends Animal {}
|
|
||||||
|
|
||||||
alert(Rabbit.__proto__ == Animal); // true
|
|
||||||
|
|
||||||
// and the next step is Function.prototype
|
|
||||||
alert(Animal.__proto__ == Function.prototype); // true
|
|
||||||
```
|
|
||||||
|
|
||||||
This way `Rabbit` has access to all static methods of `Animal`.
|
|
||||||
|
|
||||||
|
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 12 KiB |
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 28 KiB |
|
@ -0,0 +1,34 @@
|
||||||
|
class Clock {
|
||||||
|
constructor({ template }) {
|
||||||
|
this._template = template;
|
||||||
|
}
|
||||||
|
|
||||||
|
_render() {
|
||||||
|
let date = new Date();
|
||||||
|
|
||||||
|
let hours = date.getHours();
|
||||||
|
if (hours < 10) hours = '0' + hours;
|
||||||
|
|
||||||
|
let mins = date.getMinutes();
|
||||||
|
if (mins < 10) min = '0' + mins;
|
||||||
|
|
||||||
|
let secs = date.getSeconds();
|
||||||
|
if (secs < 10) secs = '0' + secs;
|
||||||
|
|
||||||
|
let output = this._template
|
||||||
|
.replace('h', hours)
|
||||||
|
.replace('m', mins)
|
||||||
|
.replace('s', secs);
|
||||||
|
|
||||||
|
console.log(output);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
clearInterval(this._timer);
|
||||||
|
}
|
||||||
|
|
||||||
|
start() {
|
||||||
|
this._render();
|
||||||
|
this._timer = setInterval(() => this._render(), 1000);
|
||||||
|
}
|
||||||
|
}
|