Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 23ffde7

Browse files
committed
minor fixes
1 parent 2acd258 commit 23ffde7

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

‎1-js/09-classes/01-class/article.md‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,6 @@ Technically, they are processed after the constructor has done it's job.
333333

334334
### Making bound methods with class fields
335335

336-
Class fields together with arrow functions can be used to create "bound" methods, with fixed `this` that always references the object.
337-
338336
As demonstrated in the chapter <info:bind> functions in JavaScript have a dynamic `this`. It depends on the context of the call.
339337

340338
So if an object method is passed around and called in another context, `this` won't be a reference to its object any more.
@@ -361,17 +359,17 @@ setTimeout(button.click, 1000); // undefined
361359

362360
The problem is called "losing `this`".
363361

364-
There are two ways to fix it, as discussed in the chapter <info:bind>:
362+
There are two approaches to fixing it, as discussed in the chapter <info:bind>:
365363

366364
1. Pass a wrapper-function, such as `setTimeout(() => button.click(), 1000)`.
367-
2. Bind the method to object in the constructor:
365+
2. Bind the method to object, e.g. in the constructor:
368366

369367
```js run
370368
class Button {
371369
constructor(value) {
372370
this.value = value;
373371
*!*
374-
this.click = this.click.bound(this);
372+
this.click = this.click.bind(this);
375373
*/!*
376374
}
377375

@@ -406,7 +404,7 @@ let button = new Button("hello");
406404
setTimeout(button.click, 1000); // hello
407405
```
408406

409-
As you can see, `click = () => {...}` creates an independent function on each `Button` object, with `this` bound to the object.
407+
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`.
410408

411409
That's especially useful in browser environment, when we need to setup a method as an event listener.
412410

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /