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
Como sabemos, objetos podem armazenar propriedades.
5
5
6
-
Until now, a property was a simple "key-value" pair to us. But an object property is actually a more flexible and powerful thing.
6
+
Até agora, para nós, uma propriedade era um simples par "chave-valor". Mas uma propriedade de objeto é na verdade uma coisa mais flexível e poderosa.
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
+
Neste capítulo, nós vamos estudar opções de configuração adicionais, e no próximo nós vamos ver como invisivelmente tornar elas em funções getter/setter.
9
9
10
-
## Property flags
10
+
## Sinalizadores de propriedade
11
11
12
-
Object properties, besides a**`value`**, have three special attributes (so-called "flags"):
12
+
Propriedades de objeto, além do**`valor`** têm três atributos especiais (também chamados "sinalizadores"):
13
13
14
-
-**`writable`** -- if`true`, the value 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
+
-**`gravável`** -- se`true`, o valor pode ser alterado, caso contrário, é apenas-leitura.
15
+
-**`enumerável`** -- se`true`, então pode ser listado em loops, caso contrário, não pode.
16
+
-**`configurável`** -- se`true`, a propriedade pode ser deletada e seus atributos modificados, caso contrário não.
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
+
Nós não vimos eles ainda, porque geralmente eles não aparecem. Quando criamos uma propriedade "do jeito comum", todos eles são `true`. Mas nós também podemos mudá-los a qualquer hora.
19
19
20
-
First, let's see how to get those flags.
20
+
Primeiro, vamos ver como obter esses sinalizadores.
21
21
22
-
The method[Object.getOwnPropertyDescriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor)allows to query the *full* information about a property.
22
+
O método[Object.getOwnPropertyDescriptor](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor)nos permite consultar a informação *completa* sobre a propriedade.
23
23
24
-
The syntax is:
24
+
A sintaxe é:
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
+
: O objeto do qual vamos obter a informação.
31
31
32
32
`propertyName`
33
-
: The name of the property.
33
+
: O nome da propriedade.
34
34
35
-
The returned value is a so-called "property descriptor" object: it contains the value and all the flags.
35
+
O valor retornado é também chamado de objeto "descritor de propriedade": ele contém o valor e todos os sinalizadores.
36
36
37
-
For instance:
37
+
Por exemplo:
38
38
39
39
```js run
40
40
let user = {
@@ -44,7 +44,7 @@ let user = {
44
44
let descriptor =Object.getOwnPropertyDescriptor(user, 'name');
To change the flags, we can use [Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
57
+
Para mudar os sinalizadores, nós podemos usar o [Object.defineProperty](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty).
: The object and its property to apply the descriptor.
66
+
: O objeto e sua propriedade para aplicar o descritor.
67
67
68
68
`descriptor`
69
-
: Property descriptor object to apply.
69
+
: Descritor de propriedade de objeto a aplicar.
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
+
Se a proprieade existe, `defineProperty`atualiza o seu sinalizador. Caso contrário, é criada uma propriedade com os sinalizadores e valor dados; neste caso, se um sinalizador não é fornecido, seu valor é assumido como`false`.
72
72
73
-
For instance, here a property`name`is created with all falsy flags:
73
+
Por exemplo, aqui a propriedade`name`é criada com todos os sinalizadores a falso:
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
+
Compare isso com o `user.name`"criado normalmente" acima: agora todos os sinalizadores são falsos. Se não é isso que queremos, então é melhor configurá-los como `true`no`descriptor`.
100
100
101
-
Now let's see effects of the flags by example.
101
+
Agora vamos ver os efeitos dos sinalizadores, por exemplo:
102
102
103
-
## Non-writable
103
+
## Não-gravável
104
104
105
-
Let's make`user.name`non-writable (can't be reassigned) by changing `writable` flag:
105
+
Vamos deixar`user.name`não-gravável (não pode ser reatribuído) alterando o sinalizador `writable`:
user.name="Pete"; // Error: Cannot assign to read only property 'name'
119
+
user.name="Pete"; // Error: Cannot assign to read only property 'name'... (Erro: não é possível a atribuição à variável de apenas leitura '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
+
Agora, ninguém pode alterar o nome do nosso usuário, a não ser que eles apliquem seus próprios `defineProperty`para sobrescrever o nosso.
124
124
125
-
```smart header="Errors appear only in strict mode"
126
-
In non-strict mode, no errors occur when writing to non-writable properties and such. But the operation still won't succeed. Flag-violating actions are just silently ignored in non-strict.
125
+
```smart header="Erros aparecem apenas em strict mode"
126
+
No modo não-estrito, os erros não ocorrem quando escrevendo em propriedades não-graváveis, etc. Mas a operação ainda assim não terá sucesso. Ações que violam os sinalizadores são apenas ignoradas silenciosamentes em modo não-estrito.
127
127
```
128
128
129
-
Here's the same example, but the property is created from scratch:
129
+
Aqui está o mesmo exemplo, mas a propriedade é criada do zero.
130
130
131
131
```js run
132
132
let user = { };
133
133
134
134
Object.defineProperty(user, "name", {
135
135
*!*
136
136
value:"John",
137
-
//for new properties we need to explicitly list what's true
137
+
//para novas proprieades, precisamos explicitamente de listar o que é true
138
138
enumerable:true,
139
139
configurable:true
140
140
*/!*
141
141
});
142
142
143
143
alert(user.name); // John
144
-
user.name="Pete"; //Error
144
+
user.name="Pete"; //Erro
145
145
```
146
146
147
-
## Non-enumerable
148
147
149
-
Now let's add a custom `toString` to `user`.
148
+
## Não-enumerável
150
149
151
-
Normally, a built-in `toString` for objects is non-enumerable, it does not show up in `for..in`. But if we add a `toString` of our own, then by default it shows up in `for..in`, like this:
150
+
Agora, vamos adicionar um `toString` customizado ao `user`.
151
+
152
+
Normalmente, um `toString` embutido em objetos é não-enumerável, e não aparece em `for..in`. Mas se nós adicionarmos um `toString` por nós mesmos, então por padrão ele aparece em `for..in`, desta forma:
152
153
153
154
```js run
154
155
let user = {
@@ -158,11 +159,11 @@ let user = {
158
159
}
159
160
};
160
161
161
-
//By default, both our properties are listed:
162
+
//Por padrão, ambas as nossas propriedades são listadas:
162
163
for (let key in user) alert(key); // name, toString
163
164
```
164
165
165
-
If we don't like it, then we can set `enumerable:false`. Then it won't appear in a `for..in` loop, just like the built-in one:
166
+
Se nós não gostarmos disso, então podemos configurar `enumerable:false`. Então ela não vai aparecer no loop `for..in`, tal como as propriedades embutidas:
There's absolutely nothing we can do with`Math.PI`.
230
+
Não há absolutamente nada que possamos fazer com`Math.PI`.
230
231
231
-
Making a property non-configurable is a one-way road. We cannot change it back with`defineProperty`.
232
+
Deixar uma propriedade não-configurável, é um caminho só de ida. Nós não podemos alterar isso novamente com`defineProperty`.
232
233
233
-
**Please note: `configurable: false` prevents changes of property flags and its deletion, while allowing to change its value.**
234
+
**A ideia de "configurable: false" é para prevenir a mudança de sinalizadores de propriedades e a sua eliminação, enquanto permite alterar o seu valor.**
234
235
235
-
Here`user.name`is non-configurable, but we can still change it (as it's writable):
236
+
Aqui`user.name`é não-configurável, mas nós ainda podemos alterá-lo (pois é gravável):
```smart header="The only attribute change possible: writable true -> false"
270
-
There's a minor exception about changing flags.
270
+
```smart header="A única alteração de atributo possível: gravável true -> false"
271
+
Há uma pequena excessão sobre alteração de flags.
271
272
272
-
We can change `writable: true` to `false` for a non-configurable property, thus preventing its value modification (to add another layer of protection). Not the other way around though.
273
+
Nós podemos mudar `writable: true` para `false` para uma propriedade não-configurável, evitando assim, sua modificação de valor (para adicionar outra camada de proteção). Mas não o contrário.
273
274
```
274
275
275
276
## Object.defineProperties
276
277
277
-
There's a method[Object.defineProperties(obj, descriptors)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties) that allows to define many properties at once.
278
+
Existe um método[Object.defineProperties(obj, descriptors)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) que permite definir várias propriedades de uma vez.
Então, nós podemos configurar várias propriedades de uma vez.
300
301
301
302
## Object.getOwnPropertyDescriptors
302
303
303
-
To get all property descriptors at once, we can use the method[Object.getOwnPropertyDescriptors(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors).
304
+
Para obter todos os sinalizadores de propriedade de uma vez, nós podemos usar o método[Object.getOwnPropertyDescriptors(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptors).
304
305
305
-
Together with`Object.defineProperties`it can be used as a "flags-aware" way of cloning an object:
306
+
Juntamente com`Object.defineProperties`isso pode ser usado como um jeito "incluindo-sinalizadores" de clonar objetos:
306
307
307
308
```js
308
309
let clone =Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));
309
310
```
310
311
311
-
Normally when we clone an object, we use an assignment to copy properties, like this:
312
+
Normalmente quando nós clonamos um objeto, nós usamos uma atribuição para copiar propriedades, desta forma:
312
313
313
314
```js
314
315
for (let key in user) {
315
316
clone[key] = user[key]
316
317
}
317
318
```
318
319
319
-
...But that does not copy flags. So if we want a "better" clone then `Object.defineProperties` is preferred.
320
+
...Mas isso não copia os sinalizadores. Assim, se nós quisermos um clone "melhor" então é preferível `Object.defineProperties`.
320
321
321
-
Another difference is that`for..in`ignores symbolic and non-enumerable properties, but`Object.getOwnPropertyDescriptors`returns *all* property descriptors including symbolic and non-enumerable ones.
322
+
Outra diferença é que`for..in`ignora propriedades simbólicas, mas`Object.getOwnPropertyDescriptors`returna *todas* as propriedades descritoras, incluindo as simbólicas e as não enumeráveis.
322
323
323
-
## Sealing an object globally
324
+
## Selando um objeto globalmente
324
325
325
-
Property descriptors work at the level of individual properties.
326
+
Descritores de propriedade atuam no mesmo nível de propriedades individuais.
326
327
327
-
There are also methods that limit access to the *whole* object:
328
+
Também existem métodos que limitam o acesso ao objeto *inteiro*:
0 commit comments