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
Finally JavaScript developers can *have `class`*. Here we have a basic class called Point:
7
+
Нарешті розробники JavaScript можуть *мати `class`*. Як приклад, ми маємо базовий клас під назвою Point:
9
8
```ts
10
9
classPoint {
11
10
x:number;
@@ -23,7 +22,7 @@ var p1 = new Point(0, 10);
23
22
var p2 =newPoint(10, 20);
24
23
var p3 =p1.add(p2); // {x:10,y:30}
25
24
```
26
-
This class generates the following JavaScript on ES5 emit:
25
+
Цей клас генерує наступний JavaScript, грунтуючись на ES5:
27
26
```ts
28
27
var Point = (function () {
29
28
function Point(x, y) {
@@ -36,10 +35,12 @@ var Point = (function () {
36
35
returnPoint;
37
36
})();
38
37
```
39
-
This is a fairly idiomatic traditional JavaScript class pattern now as a first class language construct.
38
+
Це досить ідіоматичний традиційний шаблон класу JavaScript, який тепер є мовною конструкцією першого класу.
40
39
41
40
### Inheritance
42
-
Classes in TypeScript (like other languages) support *single* inheritance using the `extends` keyword as shown below:
41
+
Наслідування.
42
+
43
+
Класи в TypeScript (як і в інших мовах) підтримують *single* наслудування (у класа може бути ліше один батьківський клас) за допомогою ключового слова `extends`, як показано нижче:
43
44
44
45
```ts
45
46
classPoint3DextendsPoint {
@@ -54,12 +55,13 @@ class Point3D extends Point {
54
55
}
55
56
}
56
57
```
57
-
If you have a constructor in your class then you *must* call the parent constructor from your constructor (TypeScript will point this out to you). This ensures that the stuff that it needs to set on `this` gets set. Followed by the call to `super` you can add any additional stuff you want to do in your constructor (here we add another member `z`).
58
-
59
-
Note that you override parent member functions easily (here we override `add`) and still use the functionality of the super class in your members (using `super.` syntax).
58
+
Якщо у вашому класі є конструктор, ви *повинні* викликати батьківський конструктор із свого конструктора (TypeScript вкаже вам на це). Це гарантує, що все, що потрібно для існування класу та ініціалізації `this`, буде встановлено. Після виклику `super` ви можете додати будь-які додаткові речі, які ви хочете зробити у вашому конструкторі (тут ми додаємо ще один член `z`).
59
+
Зауважте, що ви легко замінюєте батьківські функції-члени (тут ми перевизначаємо `add` ) і все ще використовуємо функціональність суперкласу у своїх членах (використовуючи синтаксис `super.` ).
60
60
61
61
### Statics
62
-
TypeScript classes support `static` properties that are shared by all instances of the class. A natural place to put (and access) them is on the class itself and that is what TypeScript does:
62
+
Статичні властивості класу.
63
+
64
+
Класи TypeScript підтримують статичні властивості, які є спільними для всіх екземплярів класу. Природним місцем для їх розміщення (і доступу) є сам клас, і саме це робить TypeScript:
63
65
64
66
```ts
65
67
classSomething {
@@ -74,22 +76,23 @@ var s2 = new Something();
74
76
console.log(Something.instances); // 2
75
77
```
76
78
77
-
You can have static members as well as static functions.
79
+
Ви можете мати як статичні члени, так і статичні функції.
78
80
79
81
### Access Modifiers
80
-
TypeScript supports access modifiers `public`,`private` and `protected` which determine the accessibility of a `class` member as shown below:
TypeScript підтримує модифікатори доступу `public` (публічний),`private` (приватний) та `protected` (захищений), які визначають доступність члена класу , як показано нижче:
If an access modifier is not specified it is implicitly `public` as that matches the *convenient* nature of JavaScript 🌹.
90
92
91
-
Note that at runtime (in the generated JS) these have no significance but will give you compile time errors if you use them incorrectly. An example of each is shown below:
93
+
Якщо модифікатор доступу не вказано, він неявно відкритий, оскільки це відповідає зручному характеру JavaScript 🌹.
92
94
95
+
Зверніть увагу, що під час виконання (у згенерованому JS) вони не мають значення, але викличуть помилки під час компіляції, якщо ви використовуєте їх неправильно. Приклад кожного показаний нижче:
93
96
```ts
94
97
classFooBase {
95
98
public x:number;
@@ -114,31 +117,32 @@ class FooChild extends FooBase {
114
117
}
115
118
```
116
119
117
-
As always these modifiers work for both member properties and member functions.
120
+
Як завжди, ці модифікатори працюють як для властивостей члена, так і для функцій члена.
118
121
119
122
### Abstract
120
-
`abstract` can be thought of as an access modifier. We present it separately because opposed to the previously mentioned modifiers it can be on a `class` as well as any member of the class. Having an `abstract` modifier primarily means that such functionality *cannot be directly invoked* and a child class must provide the functionality.
123
+
Абстрактний клас.
124
+
125
+
`abstract` можна розглядати як модифікатор доступу. Ми представляємо його окремо, тому що, на відміну від згаданих раніше модифікаторів, він може бути як у `class`, так і в будь-якому члені класу. Наявність `abstract` модифікатора в першу чергу означає, що така функціональність *не може бути безпосередньо викликана* , і дочірній клас повинен надавати цю функціональність.
121
126
122
-
*`abstract`**classes** cannot be directly instantiated. Instead the user must create some`class` that inherits from the `abstract class`.
127
+
*Ми не можемо створити екземпляр `abstract`**classes**. Замість цього користувач повинен створити якийсь`class`, який наслідує від `abstract class`
123
128
124
129
```ts
125
130
abstractclassFooCommand {}
126
131
127
132
classBarCommandextendsFooCommand {}
128
133
129
-
const fooCommand:FooCommand=newFooCommand(); // Cannot create an instance of an abstract class.
130
-
131
-
const barCommand =newBarCommand(); // You can create an instance of a class that inherits from an abstract class.
134
+
const fooCommand:FooCommand=newFooCommand(); // Не можно створити екземпляр (instance) класу
135
+
const barCommand =newBarCommand(); // Можно створити екземпляр класу, який є потомком абстрактного класу
132
136
```
133
137
134
-
*`abstract`**members** cannot be directly accessed and a child class must provide the functionality.
138
+
* неможливо отримати прямий доступ до`abstract`**members**, тому дочірній клас повинен забезпечувати цю функціональність.
135
139
136
140
```ts
137
141
abstractclassFooCommand {
138
142
abstract execute():string;
139
143
}
140
144
141
-
classBarErrorCommandextendsFooCommand {} // 'BarErrorCommand' needs implement abstract member 'execute'.
145
+
classBarErrorCommandextendsFooCommand {} // 'BarErrorCommand' повинен реалізувати'execute'.
142
146
143
147
classBarCommandextendsFooCommand {
144
148
execute() {
@@ -152,17 +156,19 @@ barCommand.execute(); // Command Bar executed
152
156
```
153
157
154
158
### Constructor is optional
159
+
Конструктор класу необов'язковий.
155
160
156
-
The class does not need to have a constructor. e.g. the following is perfectly fine.
161
+
Клас не потребує наявності конструктора. наприклад, наступне цілком нормально. Якщо не створити конструктор власноруч, TypeScript зробить конструктор за замовчуванням
157
162
158
163
```ts
159
164
classFoo {}
160
165
var foo =newFoo();
161
166
```
162
167
163
168
### Define using constructor
169
+
Визначення властивості за допомогою конструктора.
164
170
165
-
Having a member in a class and initializing it like below:
171
+
Наявність члена в класі та його ініціалізація, як показано нижче:
166
172
167
173
```ts
168
174
classFoo {
@@ -172,8 +178,7 @@ class Foo {
172
178
}
173
179
}
174
180
```
175
-
is such a common pattern that TypeScript provides a shorthand where you can prefix the member with an *access modifier* and it is automatically declared on the class and copied from the constructor. So the previous example can be re-written as (notice `public x:number`):
176
-
181
+
є настільки поширеним шаблоном, що TypeScript надає скорочення, де ви можете додати до члена *access modifier*, і він автоматично оголошується в класі та копіюється з конструктора. Тож попередній приклад можна переписати таким чином (зверніть увагу на `public x:numbe`r ):
177
182
```ts
178
183
classFoo {
179
184
constructor(publicx:number) {
@@ -182,8 +187,9 @@ class Foo {
182
187
```
183
188
184
189
### Property initializer
185
-
This is a nifty feature supported by TypeScript (from ES7 actually). You can initialize any member of the class outside the class constructor, useful to provide default (notice `members = []`)
190
+
Ініціалізатор властивості.
186
191
192
+
Це чудова функція, яка підтримується TypeScript (з ES7). Ви можете ініціалізувати будь-який член класу поза конструктором класу, що корисно для встановлення значення за замовчуванням (зверніть увагу на `number = []` )
`const`is a very welcomed addition offered by ES6 / TypeScript. It allows you to be immutable with variables. This is good from a documentation as well as a runtime perspective. To use const just replace`var`with`const`:
4
+
`const`є дуже бажаним доповненням, запропонованим ES6/TypeScript. Це дозволяє вам створювати змінні, значення которих не можно змінити. Це добре як з точки зору документації, так і з точки зору часу виконання. Щоб використовувати const, просто замініть`var`або `let` на`const`:
4
5
5
6
```ts
6
7
const foo =123;
7
8
```
8
9
9
-
> The syntax is much better (IMHO) than other languages that force the user to type something like`let constant foo`i.e. a variable + behavior specifier.
10
+
> Синтаксис TS набагато кращий (IMHO), ніж у інших мовах, які змушують користувача вводити щось на зразок`let constant foo`, тобто змінна + специфікатор поведінки.
10
11
11
-
`const`is a good practice for both readability and maintainability and avoids using *magic literals*e.g.
12
+
`const`є хорошою практикою як для зручності читання, так і для підтримки та уникає використання *magic literals*("магічних" значень), наприклад
12
13
13
14
```ts
14
-
//Low readability
15
+
//Низька читабельність та не зрозуміло, чому саме 10?
15
16
if (x>10) {
16
17
}
17
18
18
-
//Better!
19
+
//Краще!
19
20
const maxRows =10;
20
21
if (x>maxRows) {
21
22
}
22
23
```
23
24
24
25
#### const declarations must be initialized
25
-
The following is a compiler error:
26
+
27
+
ВАЖЛИВО! Константа повинна отримати значення при створені.
28
+
29
+
Нижче наведено помилку компілятора:
26
30
27
31
```ts
28
-
const foo; //ERROR: const declarations must be initialized
32
+
const foo; //ПОМИЛКА: необхідно ініціалізувати оголошення const
29
33
```
30
34
31
35
#### Left hand side of assignment cannot be a constant
32
-
Constants are immutable after creation, so if you try to assign them to a new value it is a compiler error:
36
+
37
+
Константи є незмінними після створення, тому якщо ви спробуєте призначити їм нове значення, це буде помилкою компілятора:
33
38
34
39
```ts
35
40
const foo =123;
36
-
foo=456; //ERROR: Left-hand side of an assignment expression cannot be a constant
41
+
foo=456; //ПОМИЛКА
37
42
```
38
43
39
44
#### Block Scoped
40
-
A `const` is block scoped like we saw with [`let`](./let.md):
45
+
46
+
`Const` має блочну область видимості , як ми бачили з [`let`](./let.md):
41
47
42
48
```ts
43
49
const foo =123;
44
50
if (true) {
45
-
const foo =456; //Allowed as its a new variable limited to this `if` block
51
+
const foo =456; //Можливо, тому що це інша знінна foo
46
52
}
47
53
```
48
54
49
55
#### Deep immutability
50
-
A `const` works with object literals as well, as far as protecting the variable *reference* is concerned:
56
+
57
+
`const` також працює з об’єктними літералами, в цьому припаді незмінною є *reference* (посилання) на змінну:
51
58
52
59
```ts
53
60
const foo = { bar: 123 };
54
-
foo= { bar: 456 }; //ERROR : Left hand side of an assignment expression cannot be a constant
61
+
foo= { bar: 456 }; //// ПОМИЛКА: не можна присвоїти змінній інший обʼєкт
55
62
```
56
63
57
-
However, it still allows sub properties of objects to be mutated, as shown below:
64
+
Однак він все ще дозволяє змінювати властивості об’єктів, як показано нижче:
58
65
59
66
```ts
60
67
const foo = { bar: 123 };
@@ -64,4 +71,4 @@ console.log(foo); // { bar: 456 }
64
71
65
72
#### Prefer const
66
73
67
-
Always use `const`, unless you plan to either lazily initialization of a variable, or do a reassignment (use `let` for those cases).
74
+
Завжди використовуйте const , якщо ви не плануєте пізніше ініціалізувати змінну, або виконати перепризначення (використовуйте let для таких випадків).
0 commit comments