Skip to content

Commit e5d0638

Browse files
committed
1-09-03 Traducido 2
1 parent b91261d commit e5d0638

2 files changed

Lines changed: 69 additions & 124 deletions

File tree

Lines changed: 1 addition & 64 deletions
Loading
Lines changed: 68 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11

2-
# Static properties and methods
2+
# Propiedades y métodos estáticos.
33

4-
We can also assign a method to the class function, not to its `"prototype"`. Such methods are called *static*.
4+
También podemos asignar métodos a la funcionalidad de una clase en sí, no a su `"prototype"`. Dichos métodos se llaman *static*.
55

6-
An example:
6+
En una clase, están precedidos por la palabra clave `static`, como esta:
77

88
```js run
99
class User {
@@ -14,24 +14,26 @@ class User {
1414
}
1515
}
1616

17-
User.staticMethod(); // true
17+
User.staticMethod(); // verdadero
1818
```
1919

20-
That actually does the same as assigning it as a function property:
20+
Eso realmente hace lo mismo que asignarlo como una propiedad directamente:
2121

22-
```js
23-
function User() { }
22+
```js run
23+
class User { }
2424

2525
User.staticMethod = function() {
2626
alert(this === User);
2727
};
28+
29+
User.staticMethod(); // verdadero
2830
```
2931

30-
The value of `this` inside `User.staticMethod()` is the class constructor `User` itself (the "object before dot" rule).
32+
El valor de `this` en la llamada `User.staticMethod()` es el mismo constructor de clase `User` (la regla "objeto antes de punto").
3133

32-
Usually, static methods are used to implement functions that belong to the class, but not to any particular object of it.
34+
Por lo general, los métodos estáticos se utilizan para implementar funciones que pertenecen a la clase, pero no a ningún objeto particular de la misma.
3335

34-
For instance, we have `Article` objects and need a function to compare them. The natural choice would be `Article.compare`, like this:
36+
Por ejemplo, tenemos objetos `Article` y necesitamos una función para compararlos. Una solución natural sería agregar el método `Article.compare`, como este:
3537

3638
```js run
3739
class Article {
@@ -47,31 +49,31 @@ class Article {
4749
*/!*
4850
}
4951

50-
// usage
52+
// uso
5153
let articles = [
52-
new Article("Mind", new Date(2019, 1, 1)),
53-
new Article("Body", new Date(2019, 0, 1)),
54+
new Article("HTML", new Date(2019, 1, 1)),
55+
new Article("CSS", new Date(2019, 0, 1)),
5456
new Article("JavaScript", new Date(2019, 11, 1))
5557
];
5658

5759
*!*
5860
articles.sort(Article.compare);
5961
*/!*
6062

61-
alert( articles[0].title ); // Body
63+
alert( articles[0].title ); // CSS
6264
```
6365

64-
Here `Article.compare` stands "over" the articles, as a means to compare them. It's not a method of an article, but rather of the whole class.
66+
Aquí `Article.compare` se encuentra "encima" de los artículos, como un medio para compararlos. No es el método de un artículo, sino de toda la clase.
6567

66-
Another example would be a so-called "factory" method. Imagine, we need few ways to create an article:
68+
Otro ejemplo sería un método llamado "factory". Imagina, necesitamos pocas formas para crear un artículo:
6769

68-
1. Create by given parameters (`title`, `date` etc).
69-
2. Create an empty article with today's date.
70-
3. ...
70+
1. Crearlo por parámetros dados (`title`,`date` etc.).
71+
2. Crear un artículo vacío con la fecha de hoy.
72+
3. ... o cualquier otra manera.
7173

72-
The first way can be implemented by the constructor. And for the second one we can make a static method of the class.
74+
La primera forma puede ser implementada por el constructor. Y para el segundo podemos hacer un método estático de la clase.
7375

74-
Like `Article.createTodays()` here:
76+
Al igual que `Article.createTodays()` aquí:
7577

7678
```js run
7779
class Article {
@@ -82,32 +84,32 @@ class Article {
8284

8385
*!*
8486
static createTodays() {
85-
// remember, this = Article
86-
return new this("Today's digest", new Date());
87+
// recuerda, this = Article
88+
return new this("Resumen de hoy", new Date());
8789
}
8890
*/!*
8991
}
9092

9193
let article = Article.createTodays();
9294

93-
alert( article.title ); // Todays digest
95+
alert( article.title ); // Resumen de hoy
9496
```
9597

96-
Now every time we need to create a today's digest, we can call `Article.createTodays()`. Once again, that's not a method of an article, but a method of the whole class.
98+
Ahora, cada vez que necesitamos crear un resumen de hoy, podemos llamar a `Article.createTodays()`. Una vez más, ese no es el método de un objeto artículo, sino el método de toda la clase.
9799

98-
Static methods are also used in database-related classes to search/save/remove entries from the database, like this:
100+
Los métodos estáticos también se utilizan en clases relacionadas con base de datos para buscar/guardar/eliminar entradas de la misma, como esta:
99101

100102
```js
101-
// assuming Article is a special class for managing articles
102-
// static method to remove the article:
103+
// suponiendo que el artículo es una clase especial para gestionar artículos
104+
// método estático para eliminar el artículo:
103105
Article.remove({id: 12345});
104106
```
105107

106-
## Static properties
108+
## Propiedades estáticas
107109

108110
[recent browser=Chrome]
109111

110-
Static properties are also possible, just like regular class properties:
112+
Las propiedades estáticas también son posibles, se ven como propiedades de clase regular, pero precedidas por `static`:
111113

112114
```js run
113115
class Article {
@@ -117,20 +119,21 @@ class Article {
117119
alert( Article.publisher ); // Ilya Kantor
118120
```
119121

120-
That is the same as a direct assignment to `Article`:
122+
Eso es lo mismo que una asignación directa a `Article`:
121123

122124
```js
123125
Article.publisher = "Ilya Kantor";
124126
```
125127

126-
## Statics and inheritance
128+
## Herencia de propiedades y métodos estáticos.
127129

128-
Statics are inherited, we can access `Parent.method` as `Child.method`.
130+
Las propiedades y métodos estáticos son heredados.
129131

130-
For instance, `Animal.compare` in the code below is inherited and accessible as `Rabbit.compare`:
132+
Por ejemplo, `Animal.compare` y `Animal.planet` en el siguiente código son heredados y accesibles como `Rabbit.compare` y `Rabbit.planet`:
131133

132134
```js run
133135
class Animal {
136+
static planet = "Tierra";
134137

135138
constructor(name, speed) {
136139
this.speed = speed;
@@ -139,7 +142,7 @@ class Animal {
139142

140143
run(speed = 0) {
141144
this.speed += speed;
142-
alert(`${this.name} runs with speed ${this.speed}.`);
145+
alert(`${this.name} corre a una velocidad de ${this.speed}.`);
143146
}
144147

145148
*!*
@@ -150,59 +153,64 @@ class Animal {
150153

151154
}
152155

153-
// Inherit from Animal
156+
// Hereda de Animal
154157
class Rabbit extends Animal {
155158
hide() {
156-
alert(`${this.name} hides!`);
159+
alert(`${this.name} se esconde!`);
157160
}
158161
}
159162

160163
let rabbits = [
161-
new Rabbit("White Rabbit", 10),
162-
new Rabbit("Black Rabbit", 5)
164+
new Rabbit("Conejo Blanco", 10),
165+
new Rabbit("Conejo Negro", 5)
163166
];
164167

165168
*!*
166169
rabbits.sort(Rabbit.compare);
167170
*/!*
168171

169-
rabbits[0].run(); // Black Rabbit runs with speed 5.
170-
```
172+
rabbits[0].run(); // Conejo Negro corre a una velocidad de 5.
171173

172-
Now we can call `Rabbit.compare` assuming that the inherited `Animal.compare` will be called.
174+
alert(Rabbit.planet); // Tierra
175+
```
173176

174-
How does it work? Again, using prototypes. As you might have already guessed, extends also gives `Rabbit` the `[[Prototype]]` reference to `Animal`.
177+
Ahora, cuando llamemos a `Rabbit.compare`, se llamará a `Animal.compare` heredado.
175178

179+
¿Como funciona? Nuevamente, usando prototipos. Como ya habrás adivinado, `extends` da a `Rabbit` el `[[Prototype]]` referente a `Animal`.
176180

177181
![](animal-rabbit-static.svg)
178182

179-
So, `Rabbit` function now inherits from `Animal` function. And `Animal` function normally has `[[Prototype]]` referencing `Function.prototype`, because it doesn't `extend` anything.
183+
Entonces, `Rabbit extends Animal` crea dos referencias `[[Prototype]]`:
180184

181-
Here, let's check that:
185+
1. La función de `Rabbit` se hereda prototípicamente de la función de `Animal`.
186+
2. `Rabbit.prototype` prototípicamente hereda de `Animal.prototype`.
187+
188+
Como resultado, la herencia funciona tanto para métodos regulares como estáticos.
189+
190+
Verifiquemos eso por código, aquí:
182191

183192
```js run
184193
class Animal {}
185194
class Rabbit extends Animal {}
186195

187-
// for static properties and methods
188-
alert(Rabbit.__proto__ === Animal); // true
196+
// para la estática
197+
alert(Rabbit.__proto__ === Animal); // verdadero
189198

190-
// and the next step is Function.prototype
191-
alert(Animal.__proto__ === Function.prototype); // true
192-
193-
// that's in addition to the "normal" prototype chain for object methods
194-
alert(Rabbit.prototype.__proto__ === Animal.prototype);
199+
// para métodos regulares
200+
alert(Rabbit.prototype.__proto__ === Animal.prototype); // verdadero
195201
```
196202

197-
This way `Rabbit` has access to all static methods of `Animal`.
203+
## Resumen
204+
205+
Los métodos estáticos se utilizan en la funcionalidad propia de la clase "en su conjunto". No se relaciona con una instancia de clase concreta.
198206

199-
## Summary
207+
Por ejemplo, un método para comparar `Article.compare (article1, article2)` o un método de fábrica `Article.createTodays()`.
200208

201-
Static methods are used for the functionality that doesn't relate to a concrete class instance, doesn't require an instance to exist, but rather belongs to the class as a whole, like `Article.compare` -- a generic method to compare two articles.
209+
Están etiquetados por la palabra `static` en la declaración de clase.
202210

203-
Static properties are used when we'd like to store class-level data, also not bound to an instance.
211+
Las propiedades estáticas se utilizan cuando queremos almacenar datos a nivel de clase, también no vinculados a una instancia.
204212

205-
The syntax is:
213+
La sintaxis es:
206214

207215
```js
208216
class MyClass {
@@ -214,13 +222,13 @@ class MyClass {
214222
}
215223
```
216224

217-
That's technically the same as assigning to the class itself:
225+
Técnicamente, la declaración estática es lo mismo que asignar a la clase misma:
218226

219227
```js
220228
MyClass.property = ...
221229
MyClass.method = ...
222230
```
223231

224-
Static properties are inherited.
232+
Las propiedades y métodos estáticos se heredan.
225233

226-
Technically, for `class B extends A` the prototype of the class `B` itself points to `A`: `B.[[Prototype]] = A`. So if a field is not found in `B`, the search continues in `A`.
234+
Para `class B extends A` el prototipo de la clase `B` en sí mismo apunta a `A`: `B.[[Prototipo]] = A`. Entonces, si no se encuentra un campo en `B`, la búsqueda continúa en `A`.

0 commit comments

Comments
 (0)