|
| 1 | +# Приватные и защищенне методы и свойства |
1 | 2 |
|
2 | | -# Private and protected properties and methods |
| 3 | +Один из важнейших принципов объектно-ориентированного программирования -- разделение внутреннего и внешнего интерфесов. |
3 | 4 |
|
4 | | -One of the most important principles of object oriented programming -- delimiting internal interface from the external one. |
| 5 | +Это обязательная практика в разработке чего-либо сложнее, чем "hello world". |
5 | 6 |
|
6 | | -That is "a must" practice in developing anything more complex than a "hello world" app. |
| 7 | +Чтобы понять этот принцип, давайте на секунду забудем о программировании и обратим взгляд на реальный мир. |
7 | 8 |
|
8 | | -To understand this, let's break away from development and turn our eyes into the real world. |
| 9 | +Устройства, которыми мы пользуемся, обычно довольно сложно устроены. Но разделение внутреннего и внешнего интерфейсов позволяет нам пользоваться ими без каких-либо проблем. |
9 | 10 |
|
10 | | -Usually, devices that we're using are quite complex. But delimiting the internal interface from the external one allows to use them without problems. |
| 11 | +## Пример из реальной жизни |
11 | 12 |
|
12 | | -## A real-life example |
13 | | - |
14 | | -For instance, a coffee machine. Simple from outside: a button, a display, a few holes...And, surely, the result -- great coffee! :) |
| 13 | +Например, кофеварка. Простая снаружи: кнопка, экран, несколько отверстий... И, конечно, как результат -- прекрасный кофе ! :) |
15 | 14 |
|
16 | 15 |  |
17 | 16 |
|
18 | | -But inside... (a picture from the repair manual) |
| 17 | +Но внутри... (картинка из инструкции по ремонту) |
19 | 18 |
|
20 | 19 |  |
21 | 20 |
|
22 | | -A lot of details. But we can use it without knowing anything. |
| 21 | +Множество деталей. Но мы можем пользоваться ею ничего об этом не зная. |
23 | 22 |
|
24 | | -Coffee machines are quite reliable, aren't they? We can use one for years, and only if something goes wrong -- bring it for repairs. |
| 23 | +Кофеварки довольно надежны, не так ли? Мы можем пользоваться ими годами, и если что то пойдет не так - отнесем в ремонт. |
25 | 24 |
|
26 | | -The secret of reliability and simplicity of a coffee machine -- all details are well-tuned and *hidden* inside. |
| 25 | +Секрет надежности и простоты кофемашины -- все детали хорошо отлажены и *спрятаны* внутри. |
27 | 26 |
|
28 | | -If we remove the protective cover from the coffee machine, then using it will be much more complex (where to press?), and dangerous (it can electrocute). |
| 27 | +Если мы снимем защитную крышку с кофемашины, то пользоваться ею будет гораздо сложнее (куда нажимать?) и опасно (может привести к поражению электрическим током). |
29 | 28 |
|
30 | | -As we'll see, in programming objects are like coffee machines. |
| 29 | +Как мы увидим, в программировании объекты похожи на кофемашины. |
31 | 30 |
|
32 | | -But in order to hide inner details, we'll use not a protective cover, but rather special syntax of the language and conventions. |
| 31 | +Но чтобы скрыть внутренние детали, мы будем использовать не защитную крышку, а специальный синтаксис языка и соглашения. |
33 | 32 |
|
34 | | -## Internal and external interface |
| 33 | +## Внутренный и внешнией интерфейсыъ |
35 | 34 |
|
36 | | -In object-oriented programming, properties and methods are split into two groups: |
| 35 | +В объектно-ориентированном программировании свойства и методы разделены на 2 группы: |
37 | 36 |
|
38 | | -- *Internal interface* -- methods and properties, accessible from other methods of the class, but not from the outside. |
39 | | -- *External interface* -- methods and properties, accessible also from outside the class. |
| 37 | +- *Внутренний интерфейс* -- методы и свойства доступны из других методов класса, но не доступны снаружи класса. |
| 38 | +- *Внешний интерфейс* -- методы и свойства доступны снаружи класса. |
40 | 39 |
|
41 | | -If we continue the analogy with the coffee machine -- what's hidden inside: a boiler tube, heating element, and so on -- is its internal interface. |
| 40 | +Если мы продолжаем аналогию с кофеваркой -- что скрыто внутри: трубка кипятильника, нагревательный элемент и т.д. -- это внутренний интерфейс. |
42 | 41 |
|
43 | | -An internal interface is used for the object to work, its details use each other. For instance, a boiler tube is attached to the heating element. |
| 42 | +Внутренний интерфейс используется для работы объекта, его детали используют друг друга. Например, трубка кипятильника прикреплена к нагревательному элементу. |
44 | 43 |
|
45 | | -But from the outside a coffee machine is closed by the protective cover, so that no one can reach those. Details are hidden and inaccessible. We can use its features via the external interface. |
| 44 | +Но снаружи кофемашина закрыта защитной крышкой, так что никто этого не может до этого добраться. Детали скрыты и недоступны. Мы можем использовать их функции через внешний интерфейс. |
46 | 45 |
|
47 | | -So, all we need to use an object is to know its external interface. We may be completely unaware how it works inside, and that's great. |
| 46 | +Итак, все, что нам нужно для использования объекта, это знать его внешний интерфейс. Мы можем совершенно не знать, как это работает внутри, и это здорово. |
48 | 47 |
|
49 | | -That was a general introduction. |
| 48 | +Это было общее введение. |
50 | 49 |
|
51 | | -In JavaScript, there are three types of properties and members: |
| 50 | +В JavaScript есть три типа свойств и членов: |
52 | 51 |
|
53 | | -- Public: accessible from anywhere. They comprise the external interface. Till now we were only using public properties and methods. |
54 | | -- Private: accessible only from inside the class. These are for the internal interface. |
| 52 | +- Публичные: доступны отовсюду. Они составляют внешний интерфейс. До этого момента мы использовали только публичные свойства и методы. |
| 53 | +- Приватные: доступны только внутри класса. Они для внутреннего интерфейса. |
55 | 54 |
|
56 | | -In many other languages there also exist "protected" fields: accessible only from inside the class and those extending it. They are also useful for the internal interface. They are in a sense more widespread than private ones, because we usually want inheriting classes to gain access to properly do the extension. |
| 55 | +Во многих других языках также существуют «защищенные» поля: доступные только внутри класса и тех, которые его расширяют. Они также полезны для внутреннего интерфейса. В некотором смысле они более распространены, чем частные, потому что мы обычно хотим, чтобы наследующие классы получали доступ для правильного выполнения расширения. |
57 | 56 |
|
58 | | -Protected fields are not implemented in JavaScript on the language level, but in practice they are very convenient, so they are emulated. |
| 57 | +Защищенные поля не представлены в JavaScript на уровне языка, но на практике они очень удобны, поэтому их эмулируют. |
59 | 58 |
|
60 | | -In the next step we'll make a coffee machine in JavaScript with all these types of properties. A coffee machine has a lot of details, we won't model them to stay simple (though we could). |
| 59 | +В следующей главе мы будем делать кофеварку на JavaScript со всеми этими типами свойств. Кофеварка имеет множество деталей, мы не будем их моделировать для простоты примера (хотя могли бы). |
61 | 60 |
|
62 | | -## Protecting "waterAmount" |
| 61 | +## Защищенное свойство "waterAmount" |
63 | 62 |
|
64 | | -Let's make a simple coffee machine class first: |
| 63 | +Давайте для начала создадим простой класс Кофеварка: |
65 | 64 |
|
66 | 65 | ```js run |
67 | 66 | class CoffeeMachine { |
68 | | - waterAmount = 0; // the amount of water inside |
| 67 | + waterAmount = 0; // количество воды внутри |
69 | 68 |
|
70 | 69 | constructor(power) { |
71 | 70 | this.power = power; |
72 | | - alert( `Created a coffee-machine, power: ${power}` ); |
| 71 | + alert( `Создана кофеварка, мощность: ${power}` ); |
73 | 72 | } |
74 | 73 |
|
75 | 74 | } |
76 | 75 |
|
77 | | -// create the coffee machine |
| 76 | +// создаем кофеварку |
78 | 77 | let coffeeMachine = new CoffeeMachine(100); |
79 | 78 |
|
80 | | -// add water |
| 79 | +// добавляем воды |
81 | 80 | coffeeMachine.waterAmount = 200; |
82 | 81 | ``` |
83 | 82 |
|
84 | | -Right now the properties `waterAmount` and `power` are public. We can easily get/set them from the outside to any value. |
| 83 | +Прямо сейчас своства `waterAmount` и `power` публичные. Мы можем легко получать и устанавливать их в любое значение извне. |
85 | 84 |
|
86 | | -Let's change `waterAmount` property to protected to have more control over it. For instance, we don't want anyone to set it below zero. |
| 85 | +Давайте изменим свойство `waterAmount` на защищенное, чтобы иметь больше контроля над ним. Например, мы не хотим, чтобы кто-либо устанавливал его ниже нуля. |
87 | 86 |
|
88 | | -**Protected properties are usually prefixed with an underscore `_`.** |
| 87 | +**Защищенные свойства обычно начинаются с префикса `_`.** |
89 | 88 |
|
90 | | -That is not enforced on the language level, but there's a convention that such properties and methods should not be accessed from the outside. Most programmers follow it. |
| 89 | +Это не применяется на уровне языка, но существует соглашение, что такие свойства и методы не должны быть доступны извне. Большинство программистов следуют этому. |
91 | 90 |
|
92 | 91 | So our property will be called `_waterAmount`: |
93 | 92 |
|
|
0 commit comments