Skip to content

Commit 96163a4

Browse files
authored
Translation of "Data types > Methods of primitives". PR #10 from stevermeister/translation
Data types > Methods of primitives
2 parents f66b0bc + 3403c98 commit 96163a4

File tree

3 files changed

+75
-73
lines changed

3 files changed

+75
-73
lines changed
Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11

2-
Try running it:
2+
Спробуйте запустити:
33

44
```js run
5-
let str = "Hello";
5+
let str = "Привіт";
66

77
str.test = 5; // (*)
88

99
alert(str.test);
1010
```
1111

12-
There may be two kinds of result:
12+
Ви можете отримати два результати:
1313
1. `undefined`
14-
2. An error.
14+
2. помилку.
1515

16-
Why? Let's replay what's happening at line `(*)`:
16+
Чому? Давайте повторимо те, що відбувається в рядку `(*)`:
1717

18-
1. When a property of `str` is accessed, a "wrapper object" is created.
19-
2. The operation with the property is carried out on it. So, the object gets the `test` property.
20-
3. The operation finishes and the "wrapper object" disappears.
18+
1. Коли ми намагаємося отримати доступ до `str`, створюється "об'єкт обгортка".
19+
2. Операція з властивістю здійснюється в ній. Отже, об'єкт отримує властивість `test`.
20+
3. Операція закінчується, і "об'єкт обгортка" зникає.
2121

22-
So, on the last line, `str` has no trace of the property. A new wrapper object for every object operation on a string.
22+
Отже, на останньому рядку `str` не має властивості. Для кожної операції створюється новий об'єкт обгортка.
2323

24-
Some browsers though may decide to further limit the programmer and disallow to assign properties to primitives at all. That's why in practice we can also see errors at line `(*)`. It's a little bit farther from the specification though.
24+
Деякі браузери можуть вирішити додатково обмежити програміста і взагалі заборонити присвоювати властивості примітивам. Тому на практиці ми можемо бачити помилки в рядку `(*)`. Але це трохи відрізняється від специфікації.
2525

26-
**This example clearly shows that primitives are not objects.**
2726

28-
They just can not store data.
27+
**Цей приклад чітко показує, що примітиви не є об'єктами.**
2928

30-
All property/method operations are performed with the help of temporary objects.
29+
Вони просто не можуть зберігати дані.
3130

31+
Всі операції з властивостями/методами виконуються за допомогою тимчасових об'єктів.

1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@ importance: 5
22

33
---
44

5-
# Can I add a string property?
5+
# Чи можна додати властивість до рядка?
66

77

8-
Consider the following code:
8+
Розглянемо наступний код:
99

1010
```js
11-
let str = "Hello";
11+
let str = "Привіт";
1212

1313
str.test = 5;
1414

1515
alert(str.test);
1616
```
1717

18-
How do you think, will it work? What will be shown?
18+
19+
Як ви думаєте, чи буде це працювати? Що буде показано?
Lines changed: 57 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,130 +1,131 @@
1-
# Methods of primitives
1+
# Методи примітивів
2+
3+
JavaScript дозволяє працювати з примітивами (рядок, число, і т.д.) так само як з об'єктами.
24

3-
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.
5+
Вони також надають методи для роботи. Ми вивчимо їх найближчим часом, але спочатку подивимось як воно працює, тому що примітиви не є об'єктами (і тут ми зробимо це ще більш зрозумілим).
46

5-
They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer).
7+
Давайте розглянемо різницю між примітивами та об'єктами.
68

7-
Let's look at the key distinctions between primitives and objects.
9+
Примітив
810

9-
A primitive
11+
- є значенням примітивного типу
12+
- існує 6 типів примітивів: `string`, `number`, `boolean`, `symbol`, `null` та `undefined`.
1013

11-
- Is a value of a primitive type.
12-
- There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null` and `undefined`.
14+
Об'єкт
1315

14-
An object
16+
- можна зберігати декілька значень як властивості.
17+
- може бути створений за допомогою `{}`, наприклад: `{name: "John", age: 30}`. В JavaScript існують й інші об'єкти; функції - це теж об'єкти.
1518

16-
- Is capable of storing multiple values as properties.
17-
- Can be created with `{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript; functions, for example, are objects.
18-
19-
One of the best things about objects is that we can store a function as one of its properties.
19+
Одна з цікавих речей щодо об'єктів полягає в тому, що ми можемо зберігати функцію як одну з його властивостей.
2020

2121
```js run
2222
let john = {
2323
name: "John",
2424
sayHi: function() {
25-
alert("Hi buddy!");
25+
alert("Привіт друже!");
2626
}
2727
};
2828

29-
john.sayHi(); // Hi buddy!
29+
john.sayHi(); // Привіт друже!
3030
```
3131

32-
So here we've made an object `john` with the method `sayHi`.
32+
Отже, ми створили об'єкт `john` з методом `sayHi`.
3333

34-
Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods.
34+
Вже існує багато вбудованих об'єктів, які працюють з датами, помилками, елементами HTML і т.д. Вони мають різні властивості і методи.
3535

36-
But, these features come with a cost!
36+
Але за все потрібно платити!
3737

38-
Objects are "heavier" than primitives. They require additional resources to support the internal machinery. But as properties and methods are very useful in programming, JavaScript engines try to optimize them to reduce the additional burden.
38+
Об'єкти "важчі", ніж примітиви. Вони вимагають додаткових ресурсів для підтримки внутрішньої обробки. Але, оскільки властивості і методи дуже корисні в програмуванні, двигун JavaScript намагається оптимізувати їх для зменшення додаткового навантаження.
3939

40-
## A primitive as an object
40+
## Примітив як об'єкт
4141

42-
Here's the paradox faced by the creator of JavaScript:
42+
Маємо парадокс, з яким стикається автор JavaScript:
4343

44-
- There are many things one would want to do with a primitive like a string or a number. It would be great to access them as methods.
45-
- Primitives must be as fast and lightweight as possible.
44+
- Є багато речей, які можна було б зробити з примітивом-рядком або числом. Було б добре отримати доступ до цих методів.
45+
- Примітиви повинні бути максимально швидкими та легкими.
4646

47-
The solution looks a little bit awkward, but here it is:
47+
Рішення виглядає трошки дивно, але так і є:
4848

49-
1. Primitives are still primitive. A single value, as desired.
50-
2. The language allows access to methods and properties of strings, numbers, booleans and symbols.
51-
3. When this happens, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
49+
1. Примітиви залишаються примітивами. Лише значення, як хотіли.
50+
2. JavaScript дозволяє отримати доступ до методів та властивостей рядків, чисел, булеанів та символів.
51+
3. Коли це трапляється, створюється спеціальний "об'єкт обгортка" з додатковою функціональністю, та потім він знищується.
5252

53-
The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods.
53+
Для кожного примітиву створюється своя "обгортка": `String`, `Number`, `Boolean` та `Symbol`. Отже, вони містять різні набори методів.
5454

55-
For instance, there exists a method [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) that returns a capitalized string.
55+
Наприклад: існує метод [str.toUpperCase()](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) якій повертає рядок з великими літерами.
5656

57-
Here's how it works:
57+
Ось як він працює:
5858

5959
```js run
60-
let str = "Hello";
60+
let str = "Привіт";
6161

62-
alert( str.toUpperCase() ); // HELLO
62+
alert( str.toUpperCase() ); // ПРИВІТ
6363
```
6464

65-
Simple, right? Here's what actually happens in `str.toUpperCase()`:
65+
Не складно, так? Ось що саме трапляється в `str.toUpperCase()`:
6666

67-
1. The string `str` is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like `toUpperCase()`.
68-
2. That method runs and returns a new string (shown by `alert`).
69-
3. The special object is destroyed, leaving the primitive `str` alone.
67+
1. Рядок `str` є примітивом. Тому під час звернення до його властивості створюється спеціальний об'єкт, який знає значення рядка і має корисні методи, такі як `toUpperCase()`.
68+
2. Цей метод виконується і повертає новий рядок (що показує `alert`).
69+
3. Спеціальний об'єкт руйнується, залишаючи лише примітив `str`.
7070

71-
So primitives can provide methods, but they still remain lightweight.
71+
Отже примітиви можуть надавати методи, але залишаються "легкими".
7272

73-
The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one.
73+
Двигун JavaScript добре оптимізує цей процес. Він навіть може пропустити створення додаткового об'єкта взагалі. Але він все ще повинен дотримуватися специфікації і вести себе так, наче він її створює.
7474

75-
A number has methods of its own, for instance, [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) rounds the number to the given precision:
75+
Число має свої методи, наприклад: [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) - округлює число до заданої точності:
7676

7777
```js run
7878
let n = 1.23456;
7979

8080
alert( n.toFixed(2) ); // 1.23
8181
```
8282

83-
We'll see more specific methods in chapters <info:number> and <info:string>.
83+
Ми переглянемо більш конкретні методи у розділах <info:number> та <info:string>.
8484

8585

86-
````warn header="Constructors `String/Number/Boolean` are for internal use only"
87-
Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`.
86+
````warn header="Конструктори `String/Number/Boolean` лише для внутрішнього використання"
87+
Деякі мови як Java дозволяють створювати "об'єкт обгортку" для примітивів явно використовуючи синтаксис як `new Number(1)` або `new Boolean(false)`.
8888

89-
In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places.
89+
У JavaScript це також можливо з історичних причин, але надзвичайно **не рекомендується**. Це призведе до непередбачуваних речей.
9090

91-
For instance:
91+
Наприклад:
9292

9393
```js run
9494
alert( typeof 1 ); // "number"
9595

9696
alert( typeof new Number(1) ); // "object"!
9797
```
9898

99-
And because what follows, `zero`, is an object, the alert will show up:
99+
та завдяки тому що `zero` об'єкт, ми побачимо алерт:
100100

101101
```js run
102102
let zero = new Number(0);
103103

104-
if (zero) { // zero is true, because it's an object
105-
alert( "zero is truthy?!?" );
104+
if (zero) { // zero є true, тому що це об'єкт
105+
alert( "zero є true?!?" );
106106
}
107107
```
108108

109-
On the other hand, using the same functions `String/Number/Boolean` without `new` is a totally sane and useful thing. They convert a value to the corresponding type: to a string, a number, or a boolean (primitive).
110109

111-
For example, this is entirely valid:
110+
З іншого боку, використання тих же самих функцій `String / Number / Boolean` без `new` є абсолютно розумною і корисною річчю. Вони перетворюють значення у відповідний тип: до рядка, числа або булевого (примітиву).
111+
112+
Наприклад, це цілком правильно:
112113
```js
113-
let num = Number("123"); // convert a string to number
114+
let num = Number("123"); // конвертує рядок в число
114115
```
115116
````
116117
117118
118-
````warn header="null/undefined have no methods"
119-
The special primitives `null` and `undefined` are exceptions. They have no corresponding "wrapper objects" and provide no methods. In a sense, they are "the most primitive".
119+
````warn header="null/undefined не мають методів"
120+
Винятки становлять спеціальні примітиви `null` і `undefined`. Вони не мають відповідних "об'єктів обгорток" і не надають ніяких методів. Ми можемо назвати їх "найпримітивнішими".
120121
121-
An attempt to access a property of such value would give the error:
122+
Спроба доступу до властивості такого значення дасть помилку:
122123
123124
```js run
124-
alert(null.test); // error
125+
alert(null.test); // помилка
125126
````
126127

127-
## Summary
128+
## Підсумки
128129

129-
- Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters.
130-
- Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.
130+
- Примітиви, крім `null` і `undefined`, дають багато корисних методів. Ми вивчимо їх у наступних розділах.
131+
- Формально, ці методи працюють через тимчасові об'єкти, але двигун JavaScript оптимізовано для швидкого виконання цих операцій, тому нам не треба хвилюватися.

0 commit comments

Comments
 (0)