This commit is contained in:
Ilya Kantor 2020-07-01 11:54:48 +03:00
parent 340ce43421
commit da9849d61a
2 changed files with 102 additions and 26 deletions

View file

@ -331,7 +331,7 @@ alert(user.name); // John
alert(User.prototype.name); // undefined
```
Technically, they are processed after the constructor has done it's job, and we can use for them complex expressions and function calls:
We can also assign values using more complex expressions and function calls:
```js run
class User {
@ -344,6 +344,7 @@ let user = new User();
alert(user.name); // John
```
### Making bound methods with class fields
As demonstrated in the chapter <info:bind> functions in JavaScript have a dynamic `this`. It depends on the context of the call.
@ -375,30 +376,9 @@ The problem is called "losing `this`".
There are two approaches to fixing it, as discussed in the chapter <info:bind>:
1. Pass a wrapper-function, such as `setTimeout(() => button.click(), 1000)`.
2. Bind the method to object, e.g. in the constructor:
2. Bind the method to object, e.g. in the constructor.
```js run
class Button {
constructor(value) {
this.value = value;
*!*
this.click = this.click.bind(this);
*/!*
}
click() {
alert(this.value);
}
}
let button = new Button("hello");
*!*
setTimeout(button.click, 1000); // hello
*/!*
```
Class fields provide a more elegant syntax for the latter solution:
Class fields provide another, quite elegant syntax:
```js run
class Button {
@ -417,9 +397,9 @@ let button = new Button("hello");
setTimeout(button.click, 1000); // hello
```
The class field `click = () => {...}` creates an independent function on each `Button` object, with `this` bound to the object. Then we can pass `button.click` around anywhere, and it will be called with the right `this`.
The class field `click = () => {...}` is created on a per-object basis, there's a separate function for each `Button` object, with `this` inside it referencing that object. We can pass `button.click` around anywhere, and the value of `this` will always be correct.
That's especially useful in browser environment, when we need to setup a method as an event listener.
That's especially useful in browser environment, for event listeners.
## Summary