Skip to content

Commit 25c66f6

Browse files
authored
Merge pull request #194 from rainvare/rainvare-patch-1
Property getters and setters
2 parents 215c76f + 039e27b commit 25c66f6

File tree

1 file changed

+43
-42
lines changed
  • 1-js/07-object-properties/02-property-accessors

1 file changed

+43
-42
lines changed

1-js/07-object-properties/02-property-accessors/article.md

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11

22
# Property getters and setters
33

4-
There are two kinds of properties.
4+
Hay dos tipos de propiedades de objetos.
55

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

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

1010
## Getters and setters
1111

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

1414
```js
1515
let obj = {
1616
*!*get propName()*/!* {
17-
// getter, the code executed on getting obj.propName
17+
// getter, el código ejecutado para obtener obj.propName
1818
},
1919

2020
*!*set propName(value)*/!* {
21-
// setter, the code executed on setting obj.propName = value
21+
// setter, el código ejecutado para asignar obj.propName = value
2222
}
2323
};
2424
```
2525

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

28-
For instance, we have a `user` object with `name` and `surname`:
28+
Por ejemplo, tenemos un objeto "usuario" con "nombre" y "apellido":
2929

3030
```js
3131
let user = {
@@ -34,7 +34,7 @@ let user = {
3434
};
3535
```
3636

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

3939
```js run
4040
let user = {
@@ -53,9 +53,9 @@ alert(user.fullName); // John Smith
5353
*/!*
5454
```
5555

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

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

6060
```js run
6161
let user = {
@@ -69,7 +69,7 @@ user.fullName = "Test"; // Error (property has only a getter)
6969
*/!*
7070
```
7171

72-
Let's fix it by adding a setter for `user.fullName`:
72+
Arreglémoslo agregando un setter para `user.fullName`:
7373

7474
```js run
7575
let user = {
@@ -87,29 +87,30 @@ let user = {
8787
*/!*
8888
};
8989

90-
// set fullName is executed with the given value.
90+
// set fullName se ejecuta con el valor dado.
9191
user.fullName = "Alice Cooper";
9292

9393
alert(user.name); // Alice
9494
alert(user.surname); // Cooper
9595
```
9696

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+
9899

99100
## Accessor descriptors
100101

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

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".
104105

105-
That is, an accessor descriptor may have:
106+
Así que un descriptor de accesos puede tener:
106107

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

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

114115
```js run
115116
let user = {
@@ -134,13 +135,13 @@ alert(user.fullName); // John Smith
134135
for(let key in user) alert(key); // name, surname
135136
```
136137

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

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

141142
```js run
142143
*!*
143-
// Error: Invalid property descriptor.
144+
// Error: Descriptor de propiedad inválido.
144145
*/!*
145146
Object.defineProperty({}, 'prop', {
146147
get() {
@@ -153,9 +154,9 @@ Object.defineProperty({}, 'prop', {
153154

154155
## Smarter getters/setters
155156

156-
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.
157158

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

160161
```js run
161162
let user = {
@@ -165,7 +166,7 @@ let user = {
165166

166167
set name(value) {
167168
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");
169170
return;
170171
}
171172
this._name = value;
@@ -175,19 +176,19 @@ let user = {
175176
user.name = "Pete";
176177
alert(user.name); // Pete
177178

178-
user.name = ""; // Name is too short...
179+
user.name = ""; // El nombre es demasiado corto...
179180
```
180181

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

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

185186

186187
## Using for compatibility
187188

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

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":
191192

192193
```js
193194
function User(name, age) {
@@ -200,7 +201,7 @@ let john = new User("John", 25);
200201
alert( john.age ); // 25
201202
```
202203

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

205206
```js
206207
function User(name, birthday) {
@@ -211,21 +212,21 @@ function User(name, birthday) {
211212
let john = new User("John", new Date(1992, 6, 1));
212213
```
213214

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"?
215216

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

218-
Let's keep it.
219+
Pues mantengámoslo.
219220

220-
Adding a getter for `age` solves the problem:
221+
Añadiendo un getter para la "edad" resuelve el problema:
221222

222223
```js run no-beautify
223224
function User(name, birthday) {
224225
this.name = name;
225226
this.birthday = birthday;
226227

227228
*!*
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
229230
Object.defineProperty(this, "age", {
230231
get() {
231232
let todayYear = new Date().getFullYear();
@@ -237,8 +238,8 @@ function User(name, birthday) {
237238

238239
let john = new User("John", new Date(1992, 6, 1));
239240

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
242243
```
243244

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

Comments
 (0)