-
Notifications
You must be signed in to change notification settings - Fork 231
Property getters and setters #194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
84d9a86
62996fc
05a92e5
f9b2439
78810a6
1ddc056
e9b0519
0988760
3cee180
c19bdf8
67303a9
0cb05bb
fc70112
039e27b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,31 @@ | ||
|
|
||
| # Property getters and setters | ||
|
|
||
| There are two kinds of properties. | ||
| Hay dos tipos de propiedades. | ||
|
|
||
| The first kind is *data properties*. We already know how to work with them. Actually, all properties that we've been using till now were data properties. | ||
| 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. | ||
|
|
||
| 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. | ||
| El segundo tipo de propiedades es algo nuevo. Son las *propiedades de los accesorios*. Estas son esencialmente funciones que trabajan en la obtención y configuración de un valor, pero que parecen propiedades normales de un código externo. | ||
|
||
|
|
||
| ## Getters and setters | ||
|
|
||
| Accessor properties are represented by "getter" and "setter" methods. In an object literal they are denoted by `get` and `set`: | ||
| Las propiedades del accesorio están representadas por los métodos "getter" y "setter". En un objeto con la notación literal se denotan por "get" y "set": | ||
|
||
|
|
||
| ```js | ||
| let obj = { | ||
| *!*get propName()*/!* { | ||
| // getter, the code executed on getting obj.propName | ||
| // getter, el código ejecutado al obtener obj.propName | ||
rainvare marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| }, | ||
|
|
||
| *!*set propName(value)*/!* { | ||
| // setter, the code executed on setting obj.propName = value | ||
| // setter, el código ejecutado al obtener obj.propName = value | ||
|
||
| } | ||
| }; | ||
| ``` | ||
|
|
||
| The getter works when `obj.propName` is read, the setter -- when it is assigned. | ||
| El getter funciona cuando se lee `obj.propName`, el setter -- cuando se asigna. | ||
joaquinelio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| For instance, we have a `user` object with `name` and `surname`: | ||
| Por ejemplo, tenemos un objeto "usuario" con "nombre" y "apellido": | ||
|
|
||
| ```js run | ||
| let user = { | ||
|
|
@@ -34,7 +34,7 @@ let user = { | |
| }; | ||
| ``` | ||
|
|
||
| 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: | ||
| Ahora queremos añadir una propiedad de "nombre completo", que debería ser "John Smith". Por supuesto, no queremos copiar-pegar la información existente, así que podemos aplicarla como un accesorio: | ||
|
||
|
|
||
| ```js run | ||
| let user = { | ||
|
|
@@ -53,11 +53,11 @@ alert(user.fullName); // John Smith | |
| */!* | ||
| ``` | ||
|
|
||
| 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. | ||
| Desde fuera, una propiedad accesoria se parece a una normal. Esa es la idea de las propiedades accesorias. No llamamos a " user.fullName" como una función, la leemos normalmente: el "getter" corre detrás de la escena. | ||
|
||
|
|
||
| As of now, `fullName` has only a getter. If we attempt to assign `user.fullName=`, there will be an error. | ||
| A partir de ahora, "Nombre completo" sólo tiene un receptor. Si intentamos asignar "user.fullName", habrá un error. | ||
joaquinelio marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Let's fix it by adding a setter for `user.fullName`: | ||
| Arreglémoslo agregando un setter para " user.fullName": | ||
rainvare marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```js run | ||
| let user = { | ||
|
|
@@ -75,39 +75,39 @@ let user = { | |
| */!* | ||
| }; | ||
|
|
||
| // set fullName is executed with the given value. | ||
| // set fullName se ejecuta con el valor dado. | ||
| user.fullName = "Alice Cooper"; | ||
|
|
||
| alert(user.name); // Alice | ||
| alert(user.surname); // Cooper | ||
| ``` | ||
|
|
||
| Now we have a "virtual" property. It is readable and writable, but in fact does not exist. | ||
| Ahora tenemos una propiedad "virtual". Esta es legible y escribible, pero de hecho no existe. | ||
|
|
||
|
||
| ```smart header="Accessor properties are only accessible with get/set" | ||
| Once a property is defined with `get prop()` or `set prop()`, it's an accessor property, not a data properety any more. | ||
| Una vez que una propiedad se define con `get prop()` o `set prop()`, es una propiedad accesoria, ya no es una propiedad de los datos. | ||
|
|
||
| - If there's a getter -- we can read `object.prop`, othrewise we can't. | ||
| - If there's a setter -- we can set `object.prop=...`, othrewise we can't. | ||
| - Si hay un getter -- podemos leer `object.prop`, de otro modo no podemos. | ||
| - Si hay un setter -- podemos fijar `object.prop=...`, de otro modo no podemos. | ||
|
|
||
| And in either case we can't `delete` an accessor property. | ||
| Y en cualquier caso no podemos "borrar" una propiedad accesoria. | ||
| ``` | ||
|
|
||
|
|
||
| ## Accessor descriptors | ||
|
|
||
| Descriptors for accessor properties are different -- as compared with data properties. | ||
| Los descriptores de las propiedades accesorias son different -- en comparación con las propiedades de los datos. | ||
|
|
||
| For accessor properties, there is no `value` and `writable`, but instead there are `get` and `set` functions. | ||
| Para las propiedades de los accesorios, no hay funciones de "valor" y "escritura", sino de "get" y "set". | ||
|
|
||
| So an accessor descriptor may have: | ||
| Así que un descriptor de accesorios puede tener: | ||
|
|
||
| - **`get`** -- a function without arguments, that works when a property is read, | ||
| - **`set`** -- a function with one argument, that is called when the property is set, | ||
| - **`enumerable`** -- same as for data properties, | ||
| - **`configurable`** -- same as for data properties. | ||
| - **`get`** -- una función sin argumentos, que funciona cuando se lee una propiedad, | ||
| - **`set`** -- una función con un argumento, que se llama cuando se establece la propiedad, | ||
| - **`enumerable`** -- lo mismo que para las propiedades de los datos, | ||
| - **`configurable`** -- lo mismo que para las propiedades de los datos. | ||
|
|
||
| For instance, to create an accessor `fullName` with `defineProperty`, we can pass a descriptor with `get` and `set`: | ||
| Por ejemplo, para crear un accesorio " Nombre Completo" con "Definir Propiedad", podemos pasar un descriptor con `get` y `set`: | ||
|
|
||
| ```js run | ||
| let user = { | ||
|
|
@@ -132,13 +132,13 @@ alert(user.fullName); // John Smith | |
| for(let key in user) alert(key); // name, surname | ||
| ``` | ||
|
|
||
| Please note once again that a property can be either an accessor or a data property, not both. | ||
| Tenga en cuenta una vez más que una propiedad puede ser un accesorio o una propiedad de datos, no ambas. | ||
|
|
||
| If we try to supply both `get` and `value` in the same descriptor, there will be an error: | ||
| Si intentamos poner tanto " get" como " valor" en el mismo descriptor, habrá un error: | ||
rainvare marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```js run | ||
| *!* | ||
| // Error: Invalid property descriptor. | ||
| // Error: Descriptor de propiedad inválido. | ||
| */!* | ||
| Object.defineProperty({}, 'prop', { | ||
| get() { | ||
|
|
@@ -151,9 +151,9 @@ Object.defineProperty({}, 'prop', { | |
|
|
||
| ## Smarter getters/setters | ||
|
|
||
| Getters/setters can be used as wrappers over "real" property values to gain more control over them. | ||
| Getters/setters pueden ser usados como envoltorios sobre valores de propiedad "reales" para obtener más control sobre ellos. | ||
|
|
||
| For instance, if we want to forbid too short names for `user`, we can store `name` in a special property `_name`. And filter assignments in the setter: | ||
| 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: | ||
|
|
||
| ```js run | ||
| let user = { | ||
|
|
@@ -163,7 +163,7 @@ let user = { | |
|
|
||
| set name(value) { | ||
| if (value.length < 4) { | ||
| alert("Name is too short, need at least 4 characters"); | ||
| alert("El nombre es demasiado corto, necesita al menos 4 caracteres"); | ||
| return; | ||
| } | ||
| this._name = value; | ||
|
|
@@ -173,17 +173,17 @@ let user = { | |
| user.name = "Pete"; | ||
| alert(user.name); // Pete | ||
|
|
||
| user.name = ""; // Name is too short... | ||
| user.name = ""; // El nombre es demasiado corto... | ||
| ``` | ||
|
|
||
| Technically, the external code may still access the name directly by using `user._name`. But there is a widely known agreement that properties starting with an underscore `"_"` are internal and should not be touched from outside the object. | ||
| 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. | ||
|
|
||
|
|
||
| ## Using for compatibility | ||
|
|
||
| One of the great ideas behind getters and setters -- they allow to take control over a "normal" data property and tweak it at any moment. | ||
| Una de las grandes ideas detrás de los getters y setters -- permiten tomar el control de una propiedad de datos "normal" y ajustarla en cualquier momento. | ||
|
|
||
| For instance, we started implementing user objects using data properties `name` and `age`: | ||
| Por ejemplo, empezamos a implementar objetos de usuario usando las propiedades de datos "nombre" y "edad": | ||
|
|
||
| ```js | ||
| function User(name, age) { | ||
|
|
@@ -196,7 +196,7 @@ let john = new User("John", 25); | |
| alert( john.age ); // 25 | ||
| ``` | ||
|
|
||
| ...But sooner or later, things may change. Instead of `age` we may decide to store `birthday`, because it's more precise and convenient: | ||
| ...Pero tarde o temprano, las cosas pueden cambiar. En lugar de "edad" podemos decidir almacenar "cumpleaños", porque es más preciso y conveniente: | ||
|
|
||
| ```js | ||
| function User(name, birthday) { | ||
|
|
@@ -207,19 +207,19 @@ function User(name, birthday) { | |
| let john = new User("John", new Date(1992, 6, 1)); | ||
| ``` | ||
|
|
||
| Now what to do with the old code that still uses `age` property? | ||
| Ahora, ¿qué hacer con el viejo código que todavía usa la propiedad de la "edad"? | ||
|
|
||
| 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 written by other people. And besides, `age` is a nice thing to have in `user`, right? In some places it's just what we want. | ||
| 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. | ||
|
|
||
| Adding a getter for `age` mitigates the problem: | ||
| Añadiendo un getter para la "edad" se atenúa el problema: | ||
|
|
||
| ```js run no-beautify | ||
| function User(name, birthday) { | ||
| this.name = name; | ||
| this.birthday = birthday; | ||
|
|
||
| *!* | ||
| // age is calculated from the current date and birthday | ||
| // La edad se calcula a partir de la fecha actual y del cumpleaños | ||
| Object.defineProperty(this, "age", { | ||
| get() { | ||
| let todayYear = new Date().getFullYear(); | ||
|
|
@@ -231,8 +231,8 @@ function User(name, birthday) { | |
|
|
||
| let john = new User("John", new Date(1992, 6, 1)); | ||
|
|
||
| alert( john.birthday ); // birthday is available | ||
| alert( john.age ); // ...as well as the age | ||
| alert( john.birthday ); // El cumpleaños está disponible | ||
| alert( john.age ); // ...así como la edad | ||
| ``` | ||
|
|
||
| Now the old code works too and we've got a nice additional property. | ||
| Ahora el viejo código funciona también y tenemos una buena propiedad adicional. | ||
Uh oh!
There was an error while loading. Please reload this page.