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
Till now, a property was a simple "key-value" pair to us. But an object property is actually a more flexible and powerful thing.
6
+
До этого момента, мы рассматривали свойство только как пару "ключ-значение". Но на самом деле, свойство объекта - это гораздо более гибкое и мощное понятие.
7
7
8
-
In this chapter we'll study additional configuration options, and in the next we'll see how to invisibly turn them into getter/setter functions.
8
+
В этой главе мы изучим дополнительные средства их конфигурации, а в следующей увидим, как легко превратить их в специальные функции - геттеры и сеттеры.
9
9
10
-
## Property flags
10
+
## Флаги свойств
11
11
12
-
Object properties, besides a **`value`**, have three special attributes (so-called "flags"):
12
+
Помимо **`значения`**, свойства объекта имеют три специальных атрибута (так называемые "флаги").
13
13
14
-
-**`writable`** -- if `true`, can be changed, otherwise it's read-only.
15
-
-**`enumerable`** -- if`true`, then listed in loops, otherwise not listed.
16
-
-**`configurable`** -- if`true`, the property can be deleted and these attributes can be modified, otherwise not.
14
+
-**`writable`** -- если значение `true`, свойство можно изменить, иначе оно только для чтения.
15
+
-**`enumerable`** -- если`true`, свойство работает в циклах, в противном случае циклы его игнорируют.
16
+
-**`configurable`** -- если`true`, свойство можно удалить, а эти атрибуты можно изменять, иначе этого делать нельзя.
17
17
18
-
We didn't see them yet, because generally they do not show up. When we create a property "the usual way", all of them are `true`. But we also can change them anytime.
18
+
Мы еще не встречали эти атрибуты, потому что они имеют скрытую реализацию. Когда мы создаем свойство "обычным способом", все эти атрибуты имеют значение `true`. Но мы можем изменить их в любое время.
19
19
20
-
First, let's see how to get those flags.
20
+
Сначала посмотрим, как получить эти флаги.
21
21
22
-
The method [Object.getOwnPropertyDescriptor](mdn:js/Object/getOwnPropertyDescriptor)allows to query the *full* information about a property.
22
+
Метод [Object.getOwnPropertyDescriptor](mdn:js/Object/getOwnPropertyDescriptor)позволяет получить *полную* информацию о свойстве.
23
23
24
-
The syntax is:
24
+
Его синтаксис:
25
25
```js
26
26
let descriptor =Object.getOwnPropertyDescriptor(obj, propertyName);
27
27
```
28
28
29
29
`obj`
30
-
: The object to get information from.
30
+
: Объект, из которого мы получаем информацию.
31
31
32
32
`propertyName`
33
-
: The name of the property.
33
+
: Имя свойства.
34
34
35
-
The returned value is a so-called "property descriptor" object: it contains the value and all the flags.
35
+
Возвращенный объект - это так называемый "дескриптор свойства": он содержит значение свойства и все его флаги.
36
36
37
-
For instance:
37
+
Например:
38
38
39
39
```js run
40
40
let user = {
@@ -44,7 +44,7 @@ let user = {
44
44
let descriptor =Object.getOwnPropertyDescriptor(user, 'name');
: Объект и свойство, с которыми мы будем работать.
67
67
68
68
`descriptor`
69
-
: Property descriptor to apply.
69
+
: Дескриптор, который описывает поведение свойства.
70
70
71
-
If the property exists, `defineProperty`updates its flags. Otherwise, it creates the property with the given value and flags; in that case, if a flag is not supplied, it is assumed`false`.
71
+
Если свойство существует, `defineProperty`обновит его флаги. В противном случае, метод создает новое свойство с указанным значением и флагами; в этом случае, если какой-либо флаг не указан явно, ему присваивается значение`false`.
72
72
73
-
For instance, here a property`name`is created with all falsy flags:
73
+
Например, все флаги свойства`name`в коде ниже создаются со значением `false`:
Compare it with "normally created" `user.name` above: now all flags are falsy. If that's not what we want then we'd better set them to `true`in `descriptor`.
99
+
Сравните этот способ с `user.name`, который мы создали выше "обычным способом": в этот раз все флаги имеют значение `false`. Если это не то, что нам нужно, надо присвоить им значения `true`в `дескрипторе`.
100
100
101
-
Now let's see effects of the flags by example.
101
+
Давайте рассмотрим на примерах, что нам дает использование флагов.
102
102
103
-
## Read-only
103
+
## Только для чтения
104
104
105
-
Let's make `user.name`read-only by changing `writable` flag:
105
+
Давайте сделаем свойство `user.name`доступным только для чтения. Для этого изменим флаг `writable`:
user.name="Pete"; //Error: Cannot assign to read only property 'name'...
119
+
user.name="Pete"; //Ошибка: Невозможно изменить доступное только для чтения свойство 'name'...
120
120
*/!*
121
121
```
122
122
123
-
Now no one can change the name of our user, unless they apply their own`defineProperty`to override ours.
123
+
Никто не сможет изменить имя пользователя, пока не переопределит наш метод`defineProperty`своим.
124
124
125
-
Here's the same operation, but for the case when a property doesn't exist:
125
+
Вот та же самая операция, но в ситуации, когда свойство не существует:
126
126
127
127
```js run
128
128
let user = { };
129
129
130
130
Object.defineProperty(user, "name", {
131
131
*!*
132
132
value:"Pete",
133
-
//for new properties need to explicitly list what's true
133
+
//для нового свойства необходимо явно указать значение true
134
134
enumerable:true,
135
135
configurable:true
136
136
*/!*
137
137
});
138
138
139
139
alert(user.name); // Pete
140
-
user.name="Alice"; //Error
140
+
user.name="Alice"; //Ошибка
141
141
```
142
142
143
143
144
-
## Non-enumerable
144
+
## Неперечисляемое свойство
145
145
146
-
Now let's add a custom `toString`to`user`.
146
+
Теперь добавим собственный метод `toString`к объекту`user`.
147
147
148
-
Normally, a built-in`toString`for objects is non-enumerable, it does not show up in `for..in`. But if we add `toString` of our own, then by default it shows up in `for..in`, like this:
148
+
Обычно, встроенный метод`toString`в объектах - неперечисляемый, он не работает в цикле `for..in`. Но если мы напишем свой собственный метод `toString`, он будет работать в цикле `for..in` по умолчанию:
149
149
150
150
```js run
151
151
let user = {
@@ -155,11 +155,11 @@ let user = {
155
155
}
156
156
};
157
157
158
-
//By default, both our properties are listed:
158
+
//По умолчанию, оба свойства работают в цикле:
159
159
for (let key in user) alert(key); // name, toString
160
160
```
161
161
162
-
If we don't like it, then we can set`enumerable:false`. Then it won't appear in `for..in` loop, just like the built-in one:
162
+
Если мы этого не хотим, можно установить для свойства`enumerable:false`. Тогда это свойство не будет работать в цикле `for..in`, как и его встроенный аналог:
So, a programmer is unable to change the value of `Math.PI`or overwrite it.
211
+
То есть, программист не сможет изменить значение `Math.PI`или перезаписать его.
212
212
213
213
```js run
214
-
Math.PI=3; //Error
214
+
Math.PI=3; //Ошибка
215
215
216
-
//delete Math.PI won't work either
216
+
//удаление Math.PI также не будет работать
217
217
```
218
218
219
-
Making a property non-configurable is a one-way road. We cannot change it back, because `defineProperty`doesn't work on non-configurable properties.
219
+
Определение свойства как неконфигурируемого - это дорога в один конец. Мы не сможем поменять это обратно, потому что `defineProperty`не работает с неконфигуриремыми свойствами.
220
220
221
-
Here we are making `user.name`a "forever sealed" constant:
221
+
В коде ниже мы делаем `user.name`"навечно запечатанной" константой:
```smart header="Errors appear only in use strict"
243
-
In the non-strict mode, no errors occur when writing to read-only properties and such. But the operation still won't succeed. Flag-violating actions are just silently ignored in non-strict.
242
+
```smart header="Ошибки отображаются только в режиме use strict"
243
+
В режиме non-strict, мы не увидим никаких ошибок при записи в свойства "только для чтения" и т.п. Но эти операции все равно не будут выполнены успешно. Действия, нарущающие ограничения флагов свойств, в режиме non-strict просто тихо игнорируются.
244
244
```
245
245
246
246
## Object.defineProperties
247
247
248
-
There's a method [Object.defineProperties(obj, descriptors)](mdn:js/Object/defineProperties) that allows to define many properties at once.
248
+
Существует метод [Object.defineProperties(obj, descriptors)](mdn:js/Object/defineProperties), который позволяет определять множество свойств сразу.
Таким образом, мы можем определить множество свойств одной операцией.
271
271
272
272
## Object.getOwnPropertyDescriptors
273
273
274
-
To get all property descriptors at once, we can use the method[Object.getOwnPropertyDescriptors(obj)](mdn:js/Object/getOwnPropertyDescriptors).
274
+
Чтобы получить все дескрипторы свойств сразу, можно воспользоваться методом[Object.getOwnPropertyDescriptors(obj)](mdn:js/Object/getOwnPropertyDescriptors).
275
275
276
-
Together with`Object.defineProperties` it can be used as a "flags-aware" way of cloning an object:
276
+
Вместе с`Object.defineProperties`, этот метод можно использовать для клонирования объекта вместе с его флагами:
277
277
278
278
```js
279
279
let clone =Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));
280
280
```
281
281
282
-
Normally when we clone an object, we use an assignment to copy properties, like this:
282
+
При клонировании объекта мы обычно используем присваивание, чтобы скопировать его свойства. Примерно так:
283
283
284
284
```js
285
285
for (let key in user) {
286
286
clone[key] = user[key]
287
287
}
288
288
```
289
289
290
-
...But that does not copy flags. So if we want a "better" clone then`Object.defineProperties` is preferred.
290
+
...Но это не копирует флаги. Так что если нам нужен клон "получше", предпочтительнее использовать`Object.defineProperties`.
291
291
292
-
Another difference is that `for..in`ignores symbolic properties, but`Object.getOwnPropertyDescriptors`returns *all* property descriptors including symbolic ones.
292
+
Другое отличие в том, что `for..in`игнорирует символические свойства, а`Object.getOwnPropertyDescriptors`возвращает дескрипторы *всех* свойств, включая символические.
293
293
294
-
## Sealing an object globally
294
+
## Глобальное запечатывание объекта
295
295
296
-
Property descriptors work at the level of individual properties.
296
+
Дескрипторы свойств работают на уровне конкретных свойств.
297
297
298
-
There are also methods that limit access to the *whole* object:
298
+
Но еще есть методы, которые ограничивают доступ ко *всему* объекту:
0 commit comments