|
1 | 1 |
|
2 | 2 | # Static properties and methods
|
3 | 3 |
|
4 |
| -We can also assign a method to the class function itself, not to its `"prototype"`. Such methods are called *static*. |
| 4 | +We can also assign a method to the class as a whole. Such methods are called *static*. |
5 | 5 |
|
6 |
| -In a class, they are prepended by `static` keyword, like this: |
| 6 | +In a class declaration, they are prepended by `static` keyword, like this: |
7 | 7 |
|
8 | 8 | ```js run
|
9 | 9 | class User {
|
@@ -31,9 +31,11 @@ User.staticMethod(); // true
|
31 | 31 |
|
32 | 32 | The value of `this` in `User.staticMethod()` call is the class constructor `User` itself (the "object before dot" rule).
|
33 | 33 |
|
34 |
| -Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it. |
| 34 | +Usually, static methods are used to implement functions that belong to the class as a whole, but not to any particular object of it. |
35 | 35 |
|
36 |
| -For instance, we have `Article` objects and need a function to compare them. A natural solution would be to add `Article.compare` method, like this: |
| 36 | +For instance, we have `Article` objects and need a function to compare them. |
| 37 | + |
| 38 | +A natural solution would be to add `Article.compare` static method: |
37 | 39 |
|
38 | 40 | ```js run
|
39 | 41 | class Article {
|
@@ -63,17 +65,19 @@ articles.sort(Article.compare);
|
63 | 65 | alert( articles[0].title ); // CSS
|
64 | 66 | ```
|
65 | 67 |
|
66 |
| -Here `Article.compare` stands "above" articles, as a means to compare them. It's not a method of an article, but rather of the whole class. |
| 68 | +Here `Article.compare` method stands "above" articles, as a means to compare them. It's not a method of an article, but rather of the whole class. |
| 69 | + |
| 70 | +Another example would be a so-called "factory" method. |
67 | 71 |
|
68 |
| -Another example would be a so-called "factory" method. Imagine, we need few ways to create an article: |
| 72 | +Let's say, we need multiple ways to create an article: |
69 | 73 |
|
70 | 74 | 1. Create by given parameters (`title`, `date` etc).
|
71 | 75 | 2. Create an empty article with today's date.
|
72 | 76 | 3. ...or else somehow.
|
73 | 77 |
|
74 | 78 | The first way can be implemented by the constructor. And for the second one we can make a static method of the class.
|
75 | 79 |
|
76 |
| -Like `Article.createTodays()` here: |
| 80 | +Such as `Article.createTodays()` here: |
77 | 81 |
|
78 | 82 | ```js run
|
79 | 83 | class Article {
|
@@ -101,7 +105,7 @@ Static methods are also used in database-related classes to search/save/remove e
|
101 | 105 |
|
102 | 106 | ```js
|
103 | 107 | // assuming Article is a special class for managing articles
|
104 |
| -// static method to remove the article: |
| 108 | +// static method to remove the article by id: |
105 | 109 | Article.remove({id: 12345});
|
106 | 110 | ```
|
107 | 111 |
|
|
0 commit comments