@@ -333,30 +333,34 @@ 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 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.
337337
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 ` :
339341
340342``` js run
341343class Button {
342344 constructor (value ) {
343345 this .value = value;
344346 }
345- * ! *
346- click = () => {
347+
348+ click () {
347349 alert (this .value );
348350 }
349- */ ! *
350351}
351352
352- let button = new Button (" button " );
353+ let button = new Button (" hello " );
353354
354- setTimeout (button .click , 1000 ); // shows "button" after 1000ms
355+ * ! *
356+ setTimeout (button .click , 1000 ); // undefined
357+ */ ! *
355358```
356359
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 > :
358361
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:
360364
361365``` js run
362366class Button {
@@ -366,9 +370,42 @@ class Button {
366370 this .click = this .click .bound (this );
367371*/ ! *
368372 }
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+ */ ! *
369398}
399+
400+ let button = new Button (" hello" );
401+
402+ setTimeout (button .click , 1000 ); // hello
370403```
371404
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+
372409## Summary
373410
374411The basic class syntax looks like this:
0 commit comments