Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Merged
Changes fromall commits
Commits
Show all changes
14 commits
Select commitHold shift + click to select a range
84d9a86
Update article.md
rainvareMay 17, 2020
62996fc
Merge branch 'master' into rainvare-patch-1
joaquinelioJun 7, 2020
05a92e5
Update article.md
rainvareJun 27, 2020
f9b2439
Update article.md
rainvareJun 28, 2020
78810a6
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
1ddc056
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
e9b0519
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
0988760
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
3cee180
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
c19bdf8
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
67303a9
Update 1-js/07-object-properties/02-property-accessors/article.md
rainvareJun 29, 2020
0cb05bb
Update article.md
rainvareJun 29, 2020
fc70112
Update 1-js/07-object-properties/02-property-accessors/article.md
joaquinelioJun 29, 2020
039e27b
Update 1-js/07-object-properties/02-property-accessors/article.md
joaquinelioJun 29, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 43 additions & 42 deletions1-js/07-object-properties/02-property-accessors/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@

# Property getters and setters

There are two kinds of properties.
Hay dos tipos de propiedades de objetos.

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

## 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 de acceso están representadas por métodos"getter"y "setter". Propiamente, en un objeto se denotan por`get`y `set`:

```js
let obj = {
*!*get propName()*/!* {
// getter,the code executed on getting obj.propName
// getter,el código ejecutado para obtener obj.propName
},

*!*set propName(value)*/!* {
// setter,the code executed on setting obj.propName = value
// setter,el código ejecutado para asignar obj.propName = value
}
};
```

The getterworks when`obj.propName` is read, the setter --when it is assigned.
El getterfunciona cuando se lee`obj.propName`, el setter --cuando se asigna.

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

```js
let user = {
Expand All@@ -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" (`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:

```js run
let user = {
Expand All@@ -53,9 +53,9 @@ alert(user.fullName); // John Smith
*/!*
```

From outside, an accessor property looks like a regular one. That's theideaof accessor properties. We don't *call*`user.fullName`as a function, we *read* it normally: thegetter runs behind the scenes.
Desde fuera, una propiedad de acceso se parece a una normal. Esa es laideade estas propiedades. 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 anerror:
A partir de ahora, "Nombre completo" sólo tiene un receptor. Si intentamos asignar`user.fullName=`,habrá unerror.

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

Let's fix it by adding asetterfor `user.fullName`:
Arreglémoslo agregando unsetterpara `user.fullName`:

```js run
let user = {
Expand All@@ -87,29 +87,30 @@ let user = {
*/!*
};

// set fullNameis executed with the given value.
// set fullNamese ejecuta con el valor dado.
user.fullName = "Alice Cooper";

alert(user.name); // Alice
alert(user.surname); // Cooper
```

As the result, we have a "virtual" property `fullName`. It is readable and writable.
Como resultado, tenemos una propiedad virtual `fullName` que puede leerse y escribirse.


## Accessor descriptors

Descriptors for accessor properties are different from those for data properties.
Los descriptores de las propiedades de acceso son diferentes de aquellos para las propiedades de los datos.

For accessor properties, there is no`value` or `writable`, but instead there are `get` and `set` functions.
Para las propiedades de acceso, nohay cosas como "valor" y "escritura", sino de "get" y "set".

That is, an accessordescriptormay have:
Así que undescriptorde accesos 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 adescriptorwith `get`and `set`:
Por ejemplo, para crear un acceso " Nombre Completo" con "Definir Propiedad", podemos pasar undescriptorcon `get`y `set`:
Copy link
Contributor

@cortizgcortizgJun 28, 2020
edited by joaquinelio
Loading

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Suggested change
Por ejemplo, para crear un acceso" Nombre Completo"con"Definir Propiedad", podemos pasar un descriptor con`get` y`set`:
Por ejemplo, para crear un acceso`fullName`con`defineProperty`, podemos pasar un descriptor con`get` y`set`:


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

Please note that a property can be either an accessor (has`get/set` methods) or a data property (has a `value`),not both.
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.

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:

```js run
*!*
// Error:Invalid property descriptor.
// Error:Descriptor de propiedad inválido.
*/!*
Object.defineProperty({}, 'prop', {
get() {
Expand All@@ -153,9 +154,9 @@ Object.defineProperty({}, 'prop', {

## Smarter getters/setters

Getters/setterscan be used as wrappers over "real" property values to gain morecontrolover operations with them.
Getters/setterspueden ser usados como envoltorios sobre valores de propiedad "reales" para obtener máscontrolsobre ellos.

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`:
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 = {
Expand All@@ -165,7 +166,7 @@ let user = {

set name(value) {
if (value.length < 4) {
alert("Name is too short, need at least 4characters");
alert("El nombre es demasiado corto, necesita al menos 4caracteres");
return;
}
this._name = value;
Expand All@@ -175,19 +176,19 @@ let user = {
user.name = "Pete";
alert(user.name); // Pete

user.name = ""; //Name is too short...
user.name = ""; //El nombre es demasiado corto...
```

So, the name is stored in`_name` property, and the access is done viagetterand setter.
Entonces, el nombre es almacenado en la propiedad`_name`, y el acceso se hace a traves degettery setter.

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.
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 uses of accessors is that they allow to take control over a "regular" data property at any moment by replacing it with agetterand asetterand tweak its behavior.
Una de los grandes usos de los getters y setters es que permiten tomar el control de una propiedad de datos "normal" y reemplazarla congetterysettery así refinar su coportamiento.

Imagine we started implementing user objects using data properties `name` and `age`:
Imagina que empezamos a implementar objetos usuario usando las propiedades de datos "nombre" y "edad":

```js
function User(name, age) {
Expand All@@ -200,7 +201,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) {
Expand All@@ -211,21 +212,21 @@ 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 used by many other people. And besides, `age` is a nice thing to have in `user`, right?
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.

Let's keep it.
Pues mantengámoslo.

Adding a getterfor `age` solves the problem:
Añadiendo un getterpara la "edad" resuelve 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();
Expand All@@ -237,8 +238,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.

[8]ページ先頭

©2009-2025 Movatter.jp