Skip to content

Commit 0424be5

Browse files
authored
Merge pull request #219 from herbertpdl/master
Property flags and descriptors
2 parents b464ad1 + 14af7c0 commit 0424be5

File tree

1 file changed

+90
-89
lines changed
  • 1-js/07-object-properties/01-property-descriptors

1 file changed

+90
-89
lines changed
Lines changed: 90 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,40 @@
11

2-
# Property flags and descriptors
2+
# Sinalizadores e descritores de propriedades
33

4-
As we know, objects can store properties.
4+
Como sabemos, objetos podem armazenar propriedades.
55

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.
77

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.
99

10-
## Property flags
10+
## Sinalizadores de propriedade
1111

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"):
1313

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.
1717

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.
1919

20-
First, let's see how to get those flags.
20+
Primeiro, vamos ver como obter esses sinalizadores.
2121

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.
2323

24-
The syntax is:
24+
A sintaxe é:
2525
```js
2626
let descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
2727
```
2828

2929
`obj`
30-
: The object to get information from.
30+
: O objeto do qual vamos obter a informação.
3131

3232
`propertyName`
33-
: The name of the property.
33+
: O nome da propriedade.
3434

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.
3636

37-
For instance:
37+
Por exemplo:
3838

3939
```js run
4040
let user = {
@@ -44,7 +44,7 @@ let user = {
4444
let descriptor = Object.getOwnPropertyDescriptor(user, 'name');
4545

4646
alert( JSON.stringify(descriptor, null, 2 ) );
47-
/* property descriptor:
47+
/* descritor de propriedade:
4848
{
4949
"value": "John",
5050
"writable": true,
@@ -54,23 +54,23 @@ alert( JSON.stringify(descriptor, null, 2 ) );
5454
*/
5555
```
5656

57-
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).
5858

59-
The syntax is:
59+
A sintaxe é:
6060

6161
```js
6262
Object.defineProperty(obj, propertyName, descriptor)
6363
```
6464

6565
`obj`, `propertyName`
66-
: The object and its property to apply the descriptor.
66+
: O objeto e sua propriedade para aplicar o descritor.
6767

6868
`descriptor`
69-
: Property descriptor object to apply.
69+
: Descritor de propriedade de objeto a aplicar.
7070

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`.
7272

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:
7474

7575
```js run
7676
let user = {};
@@ -96,13 +96,13 @@ alert( JSON.stringify(descriptor, null, 2 ) );
9696
*/
9797
```
9898

99-
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`.
100100

101-
Now let's see effects of the flags by example.
101+
Agora vamos ver os efeitos dos sinalizadores, por exemplo:
102102

103-
## Non-writable
103+
## Não-gravável
104104

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`:
106106

107107
```js run
108108
let user = {
@@ -116,39 +116,40 @@ Object.defineProperty(user, "name", {
116116
});
117117

118118
*!*
119-
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'...)
120120
*/!*
121121
```
122122

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.
124124

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.
127127
```
128128

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.
130130

131131
```js run
132132
let user = { };
133133

134134
Object.defineProperty(user, "name", {
135135
*!*
136136
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
138138
enumerable: true,
139139
configurable: true
140140
*/!*
141141
});
142142

143143
alert(user.name); // John
144-
user.name = "Pete"; // Error
144+
user.name = "Pete"; // Erro
145145
```
146146

147-
## Non-enumerable
148147

149-
Now let's add a custom `toString` to `user`.
148+
## Não-enumerável
150149

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:
152153

153154
```js run
154155
let user = {
@@ -158,11 +159,11 @@ let user = {
158159
}
159160
};
160161

161-
// By default, both our properties are listed:
162+
// Por padrão, ambas as nossas propriedades são listadas:
162163
for (let key in user) alert(key); // name, toString
163164
```
164165

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:
166167

167168
```js run
168169
let user = {
@@ -179,24 +180,24 @@ Object.defineProperty(user, "toString", {
179180
});
180181

181182
*!*
182-
// Now our toString disappears:
183+
// Agora nosso toString desaparece:
183184
*/!*
184185
for (let key in user) alert(key); // name
185186
```
186187

187-
Non-enumerable properties are also excluded from `Object.keys`:
188+
Propriedades não-enumeráveis também são excluídas de `Object.keys`:
188189

189190
```js
190191
alert(Object.keys(user)); // name
191192
```
192193

193-
## Non-configurable
194+
## Não-configurável
194195

195-
The non-configurable flag (`configurable:false`) is sometimes preset for built-in objects and properties.
196+
O sinalizador não-configurável (`configurable:false`) algumas vezes está predefinido para objetos e propriedades embutidas.
196197

197-
A non-configurable property can't be deleted, its attributes can't be modified.
198+
Uma propriedade não-configurável não pode ser deletada e seus atributos não podem ser modificador.
198199

199-
For instance, `Math.PI` is non-writable, non-enumerable and non-configurable:
200+
Por exemplo, `Math.PI` é não-gravável, não-enumerável e não-configurável:
200201

201202
```js run
202203
let descriptor = Object.getOwnPropertyDescriptor(Math, 'PI');
@@ -211,28 +212,28 @@ alert( JSON.stringify(descriptor, null, 2 ) );
211212
}
212213
*/
213214
```
214-
So, a programmer is unable to change the value of `Math.PI` or overwrite it.
215+
Então, um programador é impossibilitado de mudar o valor de `Math.PI` ou sobrescrevê-lo.
215216

216217
```js run
217-
Math.PI = 3; // Error, because it has writable: false
218+
Math.PI = 3; // Erro, porque a propriedade tem gravável: false
218219

219-
// delete Math.PI won't work either
220+
// deletar Math.PI também não irá funcionar
220221
```
221222

222-
We also can't change `Math.PI` to be `writable` again:
223+
Nós também não podemos alterar `Math.PI` para ser `writable`(gravável) de novo:
223224

224225
```js run
225-
// Error, because of configurable: false
226+
// Erro, porque configurable: false
226227
Object.defineProperty(Math, "PI", { writable: true });
227228
```
228229

229-
There's absolutely nothing we can do with `Math.PI`.
230+
Não há absolutamente nada que possamos fazer com `Math.PI`.
230231

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`.
232233

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.**
234235

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):
236237

237238
```js run
238239
let user = {
@@ -243,11 +244,11 @@ Object.defineProperty(user, "name", {
243244
configurable: false
244245
});
245246

246-
user.name = "Pete"; // works fine
247-
delete user.name; // Error
247+
user.name = "Pete"; // funciona corretamente
248+
delete user.name; // Erro
248249
```
249250

250-
And here we make `user.name` a "forever sealed" constant, just like the built-in `Math.PI`:
251+
E aqui nós deixamos `user.name` uma constante "selada para sempre", assim como a propriedade embutida `Math.PI`:
251252

252253
```js run
253254
let user = {
@@ -259,24 +260,24 @@ Object.defineProperty(user, "name", {
259260
configurable: false
260261
});
261262

262-
// won't be able to change user.name or its flags
263-
// all this won't work:
263+
// não será possível alterar user.name ou os seus sinalizadores
264+
// nada disso irá funcionar
264265
user.name = "Pete";
265266
delete user.name;
266267
Object.defineProperty(user, "name", { value: "Pete" });
267268
```
268269

269-
```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.
271272
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.
273274
```
274275

275276
## Object.defineProperties
276277

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.
278279

279-
The syntax is:
280+
A sintaxe é:
280281

281282
```js
282283
Object.defineProperties(obj, {
@@ -286,7 +287,7 @@ Object.defineProperties(obj, {
286287
});
287288
```
288289

289-
For instance:
290+
Por exemplo:
290291

291292
```js
292293
Object.defineProperties(user, {
@@ -296,54 +297,54 @@ Object.defineProperties(user, {
296297
});
297298
```
298299

299-
So, we can set many properties at once.
300+
Então, nós podemos configurar várias propriedades de uma vez.
300301

301302
## Object.getOwnPropertyDescriptors
302303

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).
304305

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:
306307

307308
```js
308309
let clone = Object.defineProperties({}, Object.getOwnPropertyDescriptors(obj));
309310
```
310311

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:
312313

313314
```js
314315
for (let key in user) {
315316
clone[key] = user[key]
316317
}
317318
```
318319

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`.
320321

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.
322323

323-
## Sealing an object globally
324+
## Selando um objeto globalmente
324325

325-
Property descriptors work at the level of individual properties.
326+
Descritores de propriedade atuam no mesmo nível de propriedades individuais.
326327

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*:
328329

329-
[Object.preventExtensions(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)
330-
: Forbids the addition of new properties to the object.
330+
[Object.preventExtensions(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)
331+
: Proíbe a adição de novas propriedades ao objeto.
331332

332-
[Object.seal(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)
333-
: Forbids adding/removing of properties. Sets `configurable: false` for all existing properties.
333+
[Object.seal(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)
334+
: Proíbe a adição/remoção de propriedades. Coloca `configurable: false` para todas as propriedades existentes.
334335

335-
[Object.freeze(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
336-
: Forbids adding/removing/changing of properties. Sets `configurable: false, writable: false` for all existing properties.
336+
[Object.freeze(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
337+
: Proíbe adicionar/remover/alterar propriedades. Coloca `configurable: false, writable: false` para todas as propriedades existentes.
337338

338-
And also there are tests for them:
339+
E também existem testes para eles:
339340

340-
[Object.isExtensible(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible)
341-
: Returns `false` if adding properties is forbidden, otherwise `true`.
341+
[Object.isExtensible(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible)
342+
: Retorna `false` se a adição de propriedades é proibida, caso contrátio `true`.
342343

343-
[Object.isSealed(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed)
344-
: Returns `true` if adding/removing properties is forbidden, and all existing properties have `configurable: false`.
344+
[Object.isSealed(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/isSealed)
345+
: Retorna `true` se adição/remoção de propriedades são proibidas, e todas as propriedades existentes são `configurable: false`.
345346

346-
[Object.isFrozen(obj)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen)
347-
: Returns `true` if adding/removing/changing properties is forbidden, and all current properties are `configurable: false, writable: false`.
347+
[Object.isFrozen(obj)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/isFrozen)
348+
: Retorna `true` se adição/remoção/alteração de propriedades são proibidas, e todas as propriedades atuais são `configurable: false, writable: false`.
348349

349-
These methods are rarely used in practice.
350+
Estes métodos são raramentes usados na prática.

0 commit comments

Comments
 (0)