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
Copy file name to clipboardExpand all lines: 1-js/07-object-properties/02-property-accessors/article.md
+43-42Lines changed: 43 additions & 42 deletions
Original file line number
Diff line number
Diff line change
@@ -1,31 +1,31 @@
1
1
2
2
# Property getters and setters
3
3
4
-
There are two kinds of properties.
4
+
Hay dos tipos de propiedades de objetos.
5
5
6
-
The first kind is *data properties*. We already know how to work with them. All properties that we've been using until now were data properties.
6
+
El primer tipo son las *propiedades de los datos*. Ya sabemos cómo trabajar con ellas. En realidad, todas las propiedades que hemos estado usando hasta ahora eran propiedades de datos.
7
7
8
-
The second type of properties is something new. It's *accessor properties*. They are essentially functions that work on getting and setting a value, but look like regular properties to an external code.
8
+
El segundo tipo de propiedades es algo nuevo. Son las *propiedades de acceso*. Estas son esencialmente funciones que se ejecutan para la obtención y asignación de un valor, pero parecen propiedades normales para un código externo.
9
9
10
10
## Getters and setters
11
11
12
-
Accessor properties are represented by "getter" and "setter" methods. In an object literal they are denoted by `get`and`set`:
12
+
Las propiedades de acceso están representadas por métodos "getter" y "setter". Propiamente, en un objeto se denotan por `get`y`set`:
13
13
14
14
```js
15
15
let obj = {
16
16
*!*get propName()*/!* {
17
-
// getter, the code executed on getting obj.propName
17
+
// getter, el código ejecutado para obtener obj.propName
18
18
},
19
19
20
20
*!*set propName(value)*/!* {
21
-
// setter, the code executed on setting obj.propName = value
21
+
// setter, el código ejecutado para asignar obj.propName = value
22
22
}
23
23
};
24
24
```
25
25
26
-
The getter works when `obj.propName` is read, the setter -- when it is assigned.
26
+
El getter funciona cuando se lee `obj.propName`, el setter -- cuando se asigna.
27
27
28
-
For instance, we have a `user` object with `name` and `surname`:
28
+
Por ejemplo, tenemos un objeto "usuario" con "nombre" y "apellido":
29
29
30
30
```js
31
31
let user = {
@@ -34,7 +34,7 @@ let user = {
34
34
};
35
35
```
36
36
37
-
Now we want to add a `fullName` property, that should be`"John Smith"`. Of course, we don't want to copy-paste existing information, so we can implement it as an accessor:
37
+
Ahora queremos añadir una propiedad de "Nombre completo" (`fullName`), que debería ser`"John Smith"`. Por supuesto, no queremos copiar-pegar la información existente, así que podemos aplicarla como una propiedad de acceso:
38
38
39
39
```js run
40
40
let user = {
@@ -53,9 +53,9 @@ alert(user.fullName); // John Smith
53
53
*/!*
54
54
```
55
55
56
-
From outside, an accessor property looks like a regular one. That's the idea of accessor properties. We don't *call*`user.fullName`as a function, we *read* it normally: the getter runs behind the scenes.
56
+
Desde fuera, una propiedad de acceso se parece a una normal. Esa es la idea de estas propiedades. No *llamamos* a `user.fullName`como una función, la *leemos* normalmente: el "getter" corre detrás de la escena.
57
57
58
-
As of now, `fullName` has only a getter. If we attempt to assign `user.fullName=`, there will be an error:
58
+
A partir de ahora, "Nombre completo" sólo tiene un receptor. Si intentamos asignar `user.fullName=`, habrá un error.
59
59
60
60
```js run
61
61
let user = {
@@ -69,7 +69,7 @@ user.fullName = "Test"; // Error (property has only a getter)
69
69
*/!*
70
70
```
71
71
72
-
Let's fix it by adding a setter for`user.fullName`:
72
+
Arreglémoslo agregando un setter para`user.fullName`:
73
73
74
74
```js run
75
75
let user = {
@@ -87,29 +87,30 @@ let user = {
87
87
*/!*
88
88
};
89
89
90
-
// set fullName is executed with the given value.
90
+
// set fullName se ejecuta con el valor dado.
91
91
user.fullName="Alice Cooper";
92
92
93
93
alert(user.name); // Alice
94
94
alert(user.surname); // Cooper
95
95
```
96
96
97
-
As the result, we have a "virtual" property `fullName`. It is readable and writable.
97
+
Como resultado, tenemos una propiedad virtual `fullName` que puede leerse y escribirse.
98
+
98
99
99
100
## Accessor descriptors
100
101
101
-
Descriptors for accessor properties are different from those for data properties.
102
+
Los descriptores de las propiedades de acceso son diferentes de aquellos para las propiedades de los datos.
102
103
103
-
For accessor properties, there is no `value` or `writable`, but instead there are `get` and `set` functions.
104
+
Para las propiedades de acceso, no hay cosas como "valor" y "escritura", sino de "get" y "set".
104
105
105
-
That is, an accessor descriptor may have:
106
+
Así que un descriptor de accesos puede tener:
106
107
107
-
-**`get`** -- a function without arguments, that works when a property is read,
108
-
-**`set`** -- a function with one argument, that is called when the property is set,
109
-
-**`enumerable`** -- same as for data properties,
110
-
-**`configurable`** -- same as for data properties.
108
+
-**`get`** -- una función sin argumentos, que funciona cuando se lee una propiedad,
109
+
-**`set`** -- una función con un argumento, que se llama cuando se establece la propiedad,
110
+
-**`enumerable`** -- lo mismo que para las propiedades de los datos,
111
+
-**`configurable`** -- lo mismo que para las propiedades de los datos.
111
112
112
-
For instance, to create an accessor `fullName` with `defineProperty`, we can pass a descriptor with`get`and`set`:
113
+
Por ejemplo, para crear un acceso " Nombre Completo" con "Definir Propiedad", podemos pasar un descriptor con`get`y`set`:
113
114
114
115
```js run
115
116
let user = {
@@ -134,13 +135,13 @@ alert(user.fullName); // John Smith
134
135
for(let key in user) alert(key); // name, surname
135
136
```
136
137
137
-
Please note that a property can be either an accessor (has `get/set` methods) or a data property (has a `value`), not both.
138
+
Tenga en cuenta que una propiedad puede ser un acceso (tiene métodos `get/set`) o una propiedad de datos (tiene un 'valor'), no ambas.
138
139
139
-
If we try to supply both `get`and `value` in the same descriptor, there will be an error:
140
+
Si intentamos poner tanto `get`como `valor` en el mismo descriptor, habrá un error:
Getters/setters can be used as wrappers over "real" property values to gain more control over operations with them.
157
+
Getters/setters pueden ser usados como envoltorios sobre valores de propiedad "reales" para obtener más control sobre ellos.
157
158
158
-
For instance, if we want to forbid too short names for `user`, we can have a setter `name` and keep the value in a separate property `_name`:
159
+
Por ejemplo, si queremos prohibir nombres demasiado cortos para "usuario", podemos guardar "nombre" en una propiedad especial "nombre". Y filtrar las asignaciones en el setter:
159
160
160
161
```js run
161
162
let user = {
@@ -165,7 +166,7 @@ let user = {
165
166
166
167
setname(value) {
167
168
if (value.length<4) {
168
-
alert("Name is too short, need at least 4 characters");
169
+
alert("El nombre es demasiado corto, necesita al menos 4 caracteres");
169
170
return;
170
171
}
171
172
this._name= value;
@@ -175,19 +176,19 @@ let user = {
175
176
user.name="Pete";
176
177
alert(user.name); // Pete
177
178
178
-
user.name=""; //Name is too short...
179
+
user.name=""; //El nombre es demasiado corto...
179
180
```
180
181
181
-
So, the name is stored in `_name` property, and the access is done via getter and setter.
182
+
Entonces, el nombre es almacenado en la propiedad `_name`, y el acceso se hace a traves de getter y setter.
182
183
183
-
Technically, external code is able to access the name directly by using `user._name`. But there is a widely known convention that properties starting with an underscore `"_"` are internal and should not be touched from outside the object.
184
+
Técnicamente, el código externo todavía puede acceder al nombre directamente usando "usuario._nombre". Pero hay un acuerdo ampliamente conocido de que las propiedades que comienzan con un guión bajo "_" son internas y no deben ser manipuladas desde el exterior del objeto.
184
185
185
186
186
187
## Using for compatibility
187
188
188
-
One of the great uses of accessors is that they allow to take control over a "regular" data property at any moment by replacing it with a getter and a setter and tweak its behavior.
189
+
Una de los grandes usos de los getters y setters es que permiten tomar el control de una propiedad de datos "normal" y reemplazarla con getter y setter y así refinar su coportamiento.
189
190
190
-
Imagine we started implementing user objects using data properties `name` and `age`:
191
+
Imagina que empezamos a implementar objetos usuario usando las propiedades de datos "nombre" y "edad":
191
192
192
193
```js
193
194
functionUser(name, age) {
@@ -200,7 +201,7 @@ let john = new User("John", 25);
200
201
alert( john.age ); // 25
201
202
```
202
203
203
-
...But sooner or later, things may change. Instead of `age` we may decide to store `birthday`, because it's more precise and convenient:
204
+
...Pero tarde o temprano, las cosas pueden cambiar. En lugar de "edad" podemos decidir almacenar "cumpleaños", porque es más preciso y conveniente:
204
205
205
206
```js
206
207
functionUser(name, birthday) {
@@ -211,21 +212,21 @@ function User(name, birthday) {
211
212
let john =newUser("John", newDate(1992, 6, 1));
212
213
```
213
214
214
-
Now what to do with the old code that still uses `age` property?
215
+
Ahora, ¿qué hacer con el viejo código que todavía usa la propiedad de la "edad"?
215
216
216
-
We can try to find all such places and fix them, but that takes time and can be hard to do if that code is used by many other people. And besides, `age` is a nice thing to have in `user`, right?
217
+
Podemos intentar encontrar todos esos lugares y arreglarlos, pero eso lleva tiempo y puede ser difícil de hacer si ese código está escrito por otras personas. Y además, la "edad" es algo bueno para tener en "usuario", ¿verdad? En algunos lugares es justo lo que queremos.
217
218
218
-
Let's keep it.
219
+
Pues mantengámoslo.
219
220
220
-
Adding a getter for `age` solves the problem:
221
+
Añadiendo un getter para la "edad" resuelve el problema:
221
222
222
223
```js run no-beautify
223
224
functionUser(name, birthday) {
224
225
this.name= name;
225
226
this.birthday= birthday;
226
227
227
228
*!*
228
-
//age is calculated from the current date and birthday
229
+
//La edad se calcula a partir de la fecha actual y del cumpleaños
229
230
Object.defineProperty(this, "age", {
230
231
get() {
231
232
let todayYear =newDate().getFullYear();
@@ -237,8 +238,8 @@ function User(name, birthday) {
237
238
238
239
let john =newUser("John", newDate(1992, 6, 1));
239
240
240
-
alert( john.birthday ); //birthday is available
241
-
alert( john.age ); // ...as well as the age
241
+
alert( john.birthday ); //El cumpleaños está disponible
242
+
alert( john.age ); // ...así como la edad
242
243
```
243
244
244
-
Now the old code works too and we've got a nice additional property.
245
+
Ahora el viejo código funciona también y tenemos una buena propiedad adicional.
0 commit comments