Skip to content

Commit 07a5bfa

Browse files
Merge pull request #11 from Netaly79/root_pages_2
Root pages 2
2 parents 8651e7d + 8dd9706 commit 07a5bfa

File tree

8 files changed

+272
-203
lines changed

8 files changed

+272
-203
lines changed

docs/classes.md

Lines changed: 41 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
### Classes
2-
The reason why it's important to have classes in JavaScript as a first class item is that:
2+
Причина, чому важливо мати класи в JavaScript як елемент першого класу, полягає в тому, що:
3+
1. [Класи пропонують корисну структурну абстракцію](./tips/classesAreUseful.md)
4+
1. Забезпечують послідовний спосіб для розробників використовувати класи замість кожного фреймворку (emberjs, reactjs тощо), створюючи власну версію.
5+
1. Об'єктно-орієнтовані розробники вже розуміють класи
36

4-
1. [Classes offer a useful structural abstraction](./tips/classesAreUseful.md)
5-
1. Provides a consistent way for developers to use classes instead of every framework (emberjs,reactjs etc) coming up with their own version.
6-
1. Object Oriented Developers already understand classes.
7-
8-
Finally JavaScript developers can *have `class`*. Here we have a basic class called Point:
7+
Нарешті розробники JavaScript можуть *мати `class`*. Як приклад, ми маємо базовий клас під назвою Point:
98
```ts
109
class Point {
1110
x: number;
@@ -23,7 +22,7 @@ var p1 = new Point(0, 10);
2322
var p2 = new Point(10, 20);
2423
var p3 = p1.add(p2); // {x:10,y:30}
2524
```
26-
This class generates the following JavaScript on ES5 emit:
25+
Цей клас генерує наступний JavaScript, грунтуючись на ES5:
2726
```ts
2827
var Point = (function () {
2928
function Point(x, y) {
@@ -36,10 +35,12 @@ var Point = (function () {
3635
return Point;
3736
})();
3837
```
39-
This is a fairly idiomatic traditional JavaScript class pattern now as a first class language construct.
38+
Це досить ідіоматичний традиційний шаблон класу JavaScript, який тепер є мовною конструкцією першого класу.
4039

4140
### Inheritance
42-
Classes in TypeScript (like other languages) support *single* inheritance using the `extends` keyword as shown below:
41+
Наслідування.
42+
43+
Класи в TypeScript (як і в інших мовах) підтримують *single* наслудування (у класа може бути ліше один батьківський клас) за допомогою ключового слова `extends`, як показано нижче:
4344

4445
```ts
4546
class Point3D extends Point {
@@ -54,12 +55,13 @@ class Point3D extends Point {
5455
}
5556
}
5657
```
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.` ).
6060

6161
### 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:
6365

6466
```ts
6567
class Something {
@@ -74,22 +76,23 @@ var s2 = new Something();
7476
console.log(Something.instances); // 2
7577
```
7678

77-
You can have static members as well as static functions.
79+
Ви можете мати як статичні члени, так і статичні функції.
7880

7981
### Access Modifiers
80-
TypeScript supports access modifiers `public`,`private` and `protected` which determine the accessibility of a `class` member as shown below:
82+
Модифікатори доступу.
8183

82-
| accessible on | `public` | `protected` | `private` |
83-
|-----------------|----------|-------------|-----------|
84-
| class | yes | yes | yes |
85-
| class children | yes | yes | no |
86-
| class instances | yes | no | no |
84+
TypeScript підтримує модифікатори доступу `public` (публічний),`private` (приватний) та `protected` (захищений), які визначають доступність члена класу , як показано нижче:
8785

86+
| доступні для | `public` | `protected` | `private` |
87+
|-----------------|----------|-------------|-----------|
88+
| клас | так | ні | так |
89+
| дочерний клас | так | так | ні |
90+
| екземпляр класу | так | ні | ні |
8891

89-
If an access modifier is not specified it is implicitly `public` as that matches the *convenient* nature of JavaScript 🌹.
9092

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 🌹.
9294

95+
Зверніть увагу, що під час виконання (у згенерованому JS) вони не мають значення, але викличуть помилки під час компіляції, якщо ви використовуєте їх неправильно. Приклад кожного показаний нижче:
9396
```ts
9497
class FooBase {
9598
public x: number;
@@ -114,31 +117,32 @@ class FooChild extends FooBase {
114117
}
115118
```
116119

117-
As always these modifiers work for both member properties and member functions.
120+
Як завжди, ці модифікатори працюють як для властивостей члена, так і для функцій члена.
118121

119122
### 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` модифікатора в першу чергу означає, що така функціональність *не може бути безпосередньо викликана* , і дочірній клас повинен надавати цю функціональність.
121126

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`
123128

124129
```ts
125130
abstract class FooCommand {}
126131

127132
class BarCommand extends FooCommand {}
128133

129-
const fooCommand: FooCommand = new FooCommand(); // Cannot create an instance of an abstract class.
130-
131-
const barCommand = new BarCommand(); // You can create an instance of a class that inherits from an abstract class.
134+
const fooCommand: FooCommand = new FooCommand(); // Не можно створити екземпляр (instance) класу
135+
const barCommand = new BarCommand(); // Можно створити екземпляр класу, який є потомком абстрактного класу
132136
```
133137

134-
* `abstract` **members** cannot be directly accessed and a child class must provide the functionality.
138+
* неможливо отримати прямий доступ до`abstract` **members**, тому дочірній клас повинен забезпечувати цю функціональність.
135139

136140
```ts
137141
abstract class FooCommand {
138142
abstract execute(): string;
139143
}
140144

141-
class BarErrorCommand extends FooCommand {} // 'BarErrorCommand' needs implement abstract member 'execute'.
145+
class BarErrorCommand extends FooCommand {} // 'BarErrorCommand' повинен реалізувати'execute'.
142146

143147
class BarCommand extends FooCommand {
144148
execute() {
@@ -152,17 +156,19 @@ barCommand.execute(); // Command Bar executed
152156
```
153157

154158
### Constructor is optional
159+
Конструктор класу необов'язковий.
155160

156-
The class does not need to have a constructor. e.g. the following is perfectly fine.
161+
Клас не потребує наявності конструктора. наприклад, наступне цілком нормально. Якщо не створити конструктор власноруч, TypeScript зробить конструктор за замовчуванням
157162

158163
```ts
159164
class Foo {}
160165
var foo = new Foo();
161166
```
162167

163168
### Define using constructor
169+
Визначення властивості за допомогою конструктора.
164170

165-
Having a member in a class and initializing it like below:
171+
Наявність члена в класі та його ініціалізація, як показано нижче:
166172

167173
```ts
168174
class Foo {
@@ -172,8 +178,7 @@ class Foo {
172178
}
173179
}
174180
```
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 ):
177182
```ts
178183
class Foo {
179184
constructor(public x:number) {
@@ -182,8 +187,9 @@ class Foo {
182187
```
183188

184189
### 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+
Ініціалізатор властивості.
186191

192+
Це чудова функція, яка підтримується TypeScript (з ES7). Ви можете ініціалізувати будь-який член класу поза конструктором класу, що корисно для встановлення значення за замовчуванням (зверніть увагу на `number = []` )
187193
```ts
188194
class Foo {
189195
members = []; // Initialize directly

docs/const.md

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,67 @@
11
### const
2+
Константи.
23

3-
`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`:
45

56
```ts
67
const foo = 123;
78
```
89

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` , тобто змінна + специфікатор поведінки.
1011
11-
`const` is a good practice for both readability and maintainability and avoids using *magic literals* e.g.
12+
`const` є хорошою практикою як для зручності читання, так і для підтримки та уникає використання *magic literals* ("магічних" значень), наприклад
1213

1314
```ts
14-
// Low readability
15+
// Низька читабельність та не зрозуміло, чому саме 10?
1516
if (x > 10) {
1617
}
1718

18-
// Better!
19+
// Краще!
1920
const maxRows = 10;
2021
if (x > maxRows) {
2122
}
2223
```
2324

2425
#### const declarations must be initialized
25-
The following is a compiler error:
26+
27+
ВАЖЛИВО! Константа повинна отримати значення при створені.
28+
29+
Нижче наведено помилку компілятора:
2630

2731
```ts
28-
const foo; // ERROR: const declarations must be initialized
32+
const foo; // ПОМИЛКА: необхідно ініціалізувати оголошення const
2933
```
3034

3135
#### 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+
Константи є незмінними після створення, тому якщо ви спробуєте призначити їм нове значення, це буде помилкою компілятора:
3338

3439
```ts
3540
const foo = 123;
36-
foo = 456; // ERROR: Left-hand side of an assignment expression cannot be a constant
41+
foo = 456; // ПОМИЛКА
3742
```
3843

3944
#### Block Scoped
40-
A `const` is block scoped like we saw with [`let`](./let.md):
45+
46+
`Const` має блочну область видимості , як ми бачили з [`let`](./let.md):
4147

4248
```ts
4349
const foo = 123;
4450
if (true) {
45-
const foo = 456; // Allowed as its a new variable limited to this `if` block
51+
const foo = 456; // Можливо, тому що це інша знінна foo
4652
}
4753
```
4854

4955
#### Deep immutability
50-
A `const` works with object literals as well, as far as protecting the variable *reference* is concerned:
56+
57+
`const` також працює з об’єктними літералами, в цьому припаді незмінною є *reference* (посилання) на змінну:
5158

5259
```ts
5360
const foo = { bar: 123 };
54-
foo = { bar: 456 }; // ERROR : Left hand side of an assignment expression cannot be a constant
61+
foo = { bar: 456 }; // // ПОМИЛКА: не можна присвоїти змінній інший обʼєкт
5562
```
5663

57-
However, it still allows sub properties of objects to be mutated, as shown below:
64+
Однак він все ще дозволяє змінювати властивості об’єктів, як показано нижче:
5865

5966
```ts
6067
const foo = { bar: 123 };
@@ -64,4 +71,4 @@ console.log(foo); // { bar: 456 }
6471

6572
#### Prefer const
6673

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

Comments
 (0)