Skip to content

Commit 879cf0a

Browse files
committed
in progress
1 parent 4624611 commit 879cf0a

1 file changed

Lines changed: 39 additions & 40 deletions

File tree

  • 1-js/09-classes/04-private-protected-properties-methods

1-js/09-classes/04-private-protected-properties-methods/article.md

Lines changed: 39 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,93 +1,92 @@
1+
# Приватные и защищенне методы и свойства
12

2-
# Private and protected properties and methods
3+
Один из важнейших принципов объектно-ориентированного программирования -- разделение внутреннего и внешнего интерфесов.
34

4-
One of the most important principles of object oriented programming -- delimiting internal interface from the external one.
5+
Это обязательная практика в разработке чего-либо сложнее, чем "hello world".
56

6-
That is "a must" practice in developing anything more complex than a "hello world" app.
7+
Чтобы понять этот принцип, давайте на секунду забудем о программировании и обратим взгляд на реальный мир.
78

8-
To understand this, let's break away from development and turn our eyes into the real world.
9+
Устройства, которыми мы пользуемся, обычно довольно сложно устроены. Но разделение внутреннего и внешнего интерфейсов позволяет нам пользоваться ими без каких-либо проблем.
910

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+
## Пример из реальной жизни
1112

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+
Например, кофеварка. Простая снаружи: кнопка, экран, несколько отверстий... И, конечно, как результат -- прекрасный кофе ! :)
1514

1615
![](coffee.jpg)
1716

18-
But inside... (a picture from the repair manual)
17+
Но внутри... (картинка из инструкции по ремонту)
1918

2019
![](coffee-inside.jpg)
2120

22-
A lot of details. But we can use it without knowing anything.
21+
Множество деталей. Но мы можем пользоваться ею ничего об этом не зная.
2322

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+
Кофеварки довольно надежны, не так ли? Мы можем пользоваться ими годами, и если что то пойдет не так - отнесем в ремонт.
2524

26-
The secret of reliability and simplicity of a coffee machine -- all details are well-tuned and *hidden* inside.
25+
Секрет надежности и простоты кофемашины -- все детали хорошо отлажены и *спрятаны* внутри.
2726

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+
Если мы снимем защитную крышку с кофемашины, то пользоваться ею будет гораздо сложнее (куда нажимать?) и опасно (может привести к поражению электрическим током).
2928

30-
As we'll see, in programming objects are like coffee machines.
29+
Как мы увидим, в программировании объекты похожи на кофемашины.
3130

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+
Но чтобы скрыть внутренние детали, мы будем использовать не защитную крышку, а специальный синтаксис языка и соглашения.
3332

34-
## Internal and external interface
33+
## Внутренный и внешнией интерфейсыъ
3534

36-
In object-oriented programming, properties and methods are split into two groups:
35+
В объектно-ориентированном программировании свойства и методы разделены на 2 группы:
3736

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+
- *Внешний интерфейс* -- методы и свойства доступны снаружи класса.
4039

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+
Если мы продолжаем аналогию с кофеваркой -- что скрыто внутри: трубка кипятильника, нагревательный элемент и т.д. -- это внутренний интерфейс.
4241

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+
Внутренний интерфейс используется для работы объекта, его детали используют друг друга. Например, трубка кипятильника прикреплена к нагревательному элементу.
4443

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+
Но снаружи кофемашина закрыта защитной крышкой, так что никто этого не может до этого добраться. Детали скрыты и недоступны. Мы можем использовать их функции через внешний интерфейс.
4645

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+
Итак, все, что нам нужно для использования объекта, это знать его внешний интерфейс. Мы можем совершенно не знать, как это работает внутри, и это здорово.
4847

49-
That was a general introduction.
48+
Это было общее введение.
5049

51-
In JavaScript, there are three types of properties and members:
50+
В JavaScript есть три типа свойств и членов:
5251

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+
- Приватные: доступны только внутри класса. Они для внутреннего интерфейса.
5554

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+
Во многих других языках также существуют «защищенные» поля: доступные только внутри класса и тех, которые его расширяют. Они также полезны для внутреннего интерфейса. В некотором смысле они более распространены, чем частные, потому что мы обычно хотим, чтобы наследующие классы получали доступ для правильного выполнения расширения.
5756

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 на уровне языка, но на практике они очень удобны, поэтому их эмулируют.
5958

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 со всеми этими типами свойств. Кофеварка имеет множество деталей, мы не будем их моделировать для простоты примера (хотя могли бы).
6160

62-
## Protecting "waterAmount"
61+
## Защищенное свойство "waterAmount"
6362

64-
Let's make a simple coffee machine class first:
63+
Давайте для начала создадим простой класс Кофеварка:
6564

6665
```js run
6766
class CoffeeMachine {
68-
waterAmount = 0; // the amount of water inside
67+
waterAmount = 0; // количество воды внутри
6968

7069
constructor(power) {
7170
this.power = power;
72-
alert( `Created a coffee-machine, power: ${power}` );
71+
alert( `Создана кофеварка, мощность: ${power}` );
7372
}
7473

7574
}
7675

77-
// create the coffee machine
76+
// создаем кофеварку
7877
let coffeeMachine = new CoffeeMachine(100);
7978

80-
// add water
79+
// добавляем воды
8180
coffeeMachine.waterAmount = 200;
8281
```
8382

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` публичные. Мы можем легко получать и устанавливать их в любое значение извне.
8584

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` на защищенное, чтобы иметь больше контроля над ним. Например, мы не хотим, чтобы кто-либо устанавливал его ниже нуля.
8786

88-
**Protected properties are usually prefixed with an underscore `_`.**
87+
**Защищенные свойства обычно начинаются с префикса `_`.**
8988

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+
Это не применяется на уровне языка, но существует соглашение, что такие свойства и методы не должны быть доступны извне. Большинство программистов следуют этому.
9190

9291
So our property will be called `_waterAmount`:
9392

0 commit comments

Comments
 (0)