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
Copy file name to clipboardExpand all lines: 1-js/09-classes/01-class/article.md
+48-4
Original file line number
Diff line number
Diff line change
@@ -298,13 +298,17 @@ class User {
298
298
newUser().sayHi();
299
299
```
300
300
301
-
## Class properties
301
+
## Class fields
302
302
303
303
```warn header="Old browsers may need a polyfill"
304
-
Class-level properties are a recent addition to the language.
304
+
Class fields are a recent addition to the language.
305
305
```
306
306
307
-
In the example above, `User` only had methods. Let's add a property:
307
+
Previously, classes only had methods.
308
+
309
+
"Class fields" is a synctax that allows to add any properties.
310
+
311
+
For instance, let's add `name` property to `class User`:
308
312
309
313
```js run
310
314
classUser {
@@ -323,7 +327,47 @@ alert(User.prototype.sayHi); // placed in User.prototype
323
327
alert(User.prototype.name); // undefined, not placed in User.prototype
324
328
```
325
329
326
-
The property `name` is not placed into `User.prototype`. Instead, it is created by `new` before calling the constructor, it's a property of the object itself.
330
+
The important thing about class fields is that they are set on individual objects, not `User.prototype`.
331
+
332
+
Technically, they are processed after the constructor has done it's job.
333
+
334
+
### Making bound methods with class fields
335
+
336
+
Class fields together with arrow functions are often used to create methods with fixed `this`, bound to the object.
337
+
338
+
In the example below, `button.click()` method always has `this = button`:
339
+
340
+
```js run
341
+
classButton {
342
+
constructor(value) {
343
+
this.value= value;
344
+
}
345
+
*!*
346
+
click= () => {
347
+
alert(this.value);
348
+
}
349
+
*/!*
350
+
}
351
+
352
+
let button =newButton("button");
353
+
354
+
setTimeout(button.click, 1000); // shows "button" after 1000ms
355
+
```
356
+
357
+
That's especially useful in browser environment, when we need to setup a method as an event listener.
0 commit comments