You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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>:
365
363
366
364
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:
368
366
369
367
```js run
370
368
classButton {
371
369
constructor(value) {
372
370
this.value= value;
373
371
*!*
374
-
this.click=this.click.bound(this);
372
+
this.click=this.click.bind(this);
375
373
*/!*
376
374
}
377
375
@@ -406,7 +404,7 @@ let button = new Button("hello");
406
404
setTimeout(button.click, 1000); // hello
407
405
```
408
406
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`.
410
408
411
409
That's especially useful in browser environment, when we need to setup a method as an event listener.
0 commit comments