@@ -333,30 +333,34 @@ Technically, they are processed after the constructor has done it's job.
333
333
334
334
### Making bound methods with class fields
335
335
336
- Class fields together with arrow functions are often used to create methods with fixed ` this ` , bound to the object.
336
+ Class fields together with arrow functions are often used to create methods with fixed ` this ` , that always references the object.
337
337
338
- In the example below, ` button.click() ` method always has ` this = button ` :
338
+ As demonstrated in the chapter < info:bind > , object methods, just like any functions, have a dynamic ` this ` . It depends on the context of the call.
339
+
340
+ So, for instance, this code will show ` undefined ` :
339
341
340
342
``` js run
341
343
class Button {
342
344
constructor (value ) {
343
345
this .value = value;
344
346
}
345
- * ! *
346
- click = () => {
347
+
348
+ click () {
347
349
alert (this .value );
348
350
}
349
- */ ! *
350
351
}
351
352
352
- let button = new Button (" button " );
353
+ let button = new Button (" hello " );
353
354
354
- setTimeout (button .click , 1000 ); // shows "button" after 1000ms
355
+ * ! *
356
+ setTimeout (button .click , 1000 ); // undefined
357
+ */ ! *
355
358
```
356
359
357
- That's especially useful in browser environment, when we need to setup a method as an event listener.
360
+ There are two ways to fix this, as discussed in the chapter < info:bind > :
358
361
359
- The same thing coded less elegantly:
362
+ 1 . Pass a wrapper-function, such as ` setTimeout(() => button.click(), 1000) ` .
363
+ 2 . Bind the method to object in the constructor:
360
364
361
365
``` js run
362
366
class Button {
@@ -366,9 +370,42 @@ class Button {
366
370
this .click = this .click .bound (this );
367
371
*/ ! *
368
372
}
373
+
374
+ click () {
375
+ alert (this .value );
376
+ }
377
+ }
378
+
379
+ let button = new Button (" hello" );
380
+
381
+ * ! *
382
+ setTimeout (button .click , 1000 ); // hello
383
+ */ ! *
384
+ ```
385
+
386
+ Class fields provide a more elegant syntax for the latter solution:
387
+
388
+ ``` js run
389
+ class Button {
390
+ constructor (value ) {
391
+ this .value = value;
392
+ }
393
+ * ! *
394
+ click = () => {
395
+ alert (this .value );
396
+ }
397
+ */ ! *
369
398
}
399
+
400
+ let button = new Button (" hello" );
401
+
402
+ setTimeout (button .click , 1000 ); // hello
370
403
```
371
404
405
+ As you can see, ` click = () => {...} ` creates an independent function on each ` Button ` object, with ` this ` bound to the object.
406
+
407
+ That's especially useful in browser environment, when we need to setup a method as an event listener.
408
+
372
409
## Summary
373
410
374
411
The basic class syntax looks like this:
0 commit comments