Skip to content

Commit d84673a

Browse files
committed
closes #1810
1 parent a55b99c commit d84673a

File tree

1 file changed

+48
-4
lines changed

1 file changed

+48
-4
lines changed

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

+48-4
Original file line numberDiff line numberDiff line change
@@ -298,13 +298,17 @@ class User {
298298
new User().sayHi();
299299
```
300300

301-
## Class properties
301+
## Class fields
302302

303303
```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.
305305
```
306306

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`:
308312

309313
```js run
310314
class User {
@@ -323,7 +327,47 @@ alert(User.prototype.sayHi); // placed in User.prototype
323327
alert(User.prototype.name); // undefined, not placed in User.prototype
324328
```
325329

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+
class Button {
342+
constructor(value) {
343+
this.value = value;
344+
}
345+
*!*
346+
click = () => {
347+
alert(this.value);
348+
}
349+
*/!*
350+
}
351+
352+
let button = new Button("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.
358+
359+
The same thing coded less elegantly:
360+
361+
```js run
362+
class Button {
363+
constructor(value) {
364+
this.value = value;
365+
*!*
366+
this.click = this.click.bound(this);
367+
*/!*
368+
}
369+
}
370+
```
327371

328372
## Summary
329373

0 commit comments

Comments
 (0)