Skip to content

Commit 05f7589

Browse files
authored
Merge pull request #172 from cortizg/es.javascript.info.1-09-03
Static properties and methods Prueba... hacer un merge con repo borrado. Si ande habria que agregar lineas en blanco 97 y 135
2 parents 243f044 + 32084d2 commit 05f7589

File tree

1 file changed

+58
-60
lines changed
  • 1-js/09-classes/03-static-properties-methods

1 file changed

+58
-60
lines changed
Lines changed: 58 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 itself, 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-
In a class, they are prepended by `static` keyword, like this:
6+
En una clase, están precedidos por la palabra clave `static`, como esta:
77

88
```js run
99
class User {
@@ -14,10 +14,10 @@ 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 property directly:
20+
Eso realmente hace lo mismo que asignarlo como una propiedad directamente:
2121

2222
```js run
2323
class User { }
@@ -26,14 +26,14 @@ User.staticMethod = function() {
2626
alert(this === User);
2727
};
2828

29-
User.staticMethod(); // true
29+
User.staticMethod(); // verdadero
3030
```
3131

32-
The value of `this` in `User.staticMethod()` call 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").
3333

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

36-
For instance, we have `Article` objects and need a function to compare them. A natural solution would be to add `Article.compare` method, 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:
3737

3838
```js run
3939
class Article {
@@ -49,7 +49,7 @@ class Article {
4949
*/!*
5050
}
5151

52-
// usage
52+
// uso
5353
let articles = [
5454
new Article("HTML", new Date(2019, 1, 1)),
5555
new Article("CSS", new Date(2019, 0, 1)),
@@ -63,17 +63,17 @@ articles.sort(Article.compare);
6363
alert( articles[0].title ); // CSS
6464
```
6565

66-
Here `Article.compare` stands "above" 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.
6767

68-
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:
6969

70-
1. Create by given parameters (`title`, `date` etc).
71-
2. Create an empty article with today's date.
72-
3. ...or else somehow.
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.
7373

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

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

7878
```js run
7979
class Article {
@@ -84,32 +84,31 @@ class Article {
8484

8585
*!*
8686
static createTodays() {
87-
// remember, this = Article
88-
return new this("Today's digest", new Date());
87+
// recuerda, this = Article
88+
return new this("Resumen de hoy", new Date());
8989
}
9090
*/!*
9191
}
9292

9393
let article = Article.createTodays();
9494

95-
alert( article.title ); // Today's digest
95+
alert( article.title ); // Resumen de hoy
9696
```
97+
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.
9798

98-
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.
99-
100-
Static methods are also used in database-related classes to search/save/remove entries from the database, like this:
99+
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:
101100

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

108-
## Static properties
107+
## Propiedades estáticas
109108

110109
[recent browser=Chrome]
111110

112-
Static properties are also possible, they look like regular class properties, but prepended by `static`:
111+
Las propiedades estáticas también son posibles, se ven como propiedades de clase regular, pero precedidas por `static`:
113112

114113
```js run
115114
class Article {
@@ -119,30 +118,29 @@ class Article {
119118
alert( Article.publisher ); // Ilya Kantor
120119
```
121120

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

124123
```js
125124
Article.publisher = "Ilya Kantor";
126125
```
127126

128-
## Inheritance of static properties and methods
127+
## Herencia de propiedades y métodos estáticos.
129128

130-
Static properties and methods are inherited.
129+
Las propiedades y métodos estáticos son heredados.
131130

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

134133
```js run
135134
class Animal {
136-
static planet = "Earth";
137-
135+
static planet = "Tierra";
138136
constructor(name, speed) {
139137
this.speed = speed;
140138
this.name = name;
141139
}
142140

143141
run(speed = 0) {
144142
this.speed += speed;
145-
alert(`${this.name} runs with speed ${this.speed}.`);
143+
alert(`${this.name} corre a una velocidad de ${this.speed}.`);
146144
}
147145

148146
*!*
@@ -153,64 +151,64 @@ class Animal {
153151

154152
}
155153

156-
// Inherit from Animal
154+
// Hereda de Animal
157155
class Rabbit extends Animal {
158156
hide() {
159-
alert(`${this.name} hides!`);
157+
alert(`${this.name} se esconde!`);
160158
}
161159
}
162160

163161
let rabbits = [
164-
new Rabbit("White Rabbit", 10),
165-
new Rabbit("Black Rabbit", 5)
162+
new Rabbit("Conejo Blanco", 10),
163+
new Rabbit("Conejo Negro", 5)
166164
];
167165

168166
*!*
169167
rabbits.sort(Rabbit.compare);
170168
*/!*
171169

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

174-
alert(Rabbit.planet); // Earth
172+
alert(Rabbit.planet); // Tierra
175173
```
176174

177-
Now when we call `Rabbit.compare`, the inherited `Animal.compare` will be called.
175+
Ahora, cuando llamemos a `Rabbit.compare`, se llamará a `Animal.compare` heredado.
178176

179-
How does it work? Again, using prototypes. As you might have already guessed, `extends` gives `Rabbit` the `[[Prototype]]` reference to `Animal`.
177+
¿Como funciona? Nuevamente, usando prototipos. Como ya habrás adivinado, `extends` da a `Rabbit` el `[[Prototype]]` referente a `Animal`.
180178

181179
![](animal-rabbit-static.svg)
182180

183-
So, `Rabbit extends Animal` creates two `[[Prototype]]` references:
181+
Entonces, `Rabbit extends Animal` crea dos referencias `[[Prototype]]`:
184182

185-
1. `Rabbit` function prototypally inherits from `Animal` function.
186-
2. `Rabbit.prototype` prototypally inherits from `Animal.prototype`.
183+
1. La función de `Rabbit` se hereda prototípicamente de la función de `Animal`.
184+
2. `Rabbit.prototype` prototípicamente hereda de `Animal.prototype`.
187185

188-
As a result, inheritance works both for regular and static methods.
186+
Como resultado, la herencia funciona tanto para métodos regulares como estáticos.
189187

190-
Here, let's check that by code:
188+
Verifiquemos eso por código, aquí:
191189

192190
```js run
193191
class Animal {}
194192
class Rabbit extends Animal {}
195193

196-
// for statics
197-
alert(Rabbit.__proto__ === Animal); // true
194+
// para la estática
195+
alert(Rabbit.__proto__ === Animal); // verdadero
198196

199-
// for regular methods
200-
alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
197+
// para métodos regulares
198+
alert(Rabbit.prototype.__proto__ === Animal.prototype); // verdadero
201199
```
202200

203-
## Summary
201+
## Resumen
204202

205-
Static methods are used for the functionality that belongs to the class "as a whole". It doesn't relate to a concrete class instance.
203+
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.
206204

207-
For example, a method for comparison `Article.compare(article1, article2)` or a factory method `Article.createTodays()`.
205+
Por ejemplo, un método para comparar `Article.compare (article1, article2)` o un método de fábrica `Article.createTodays()`.
208206

209-
They are labeled by the word `static` in class declaration.
207+
Están etiquetados por la palabra `static` en la declaración de clase.
210208

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

213-
The syntax is:
211+
La sintaxis es:
214212

215213
```js
216214
class MyClass {
@@ -222,13 +220,13 @@ class MyClass {
222220
}
223221
```
224222

225-
Technically, static declaration is the same as assigning to the class itself:
223+
Técnicamente, la declaración estática es lo mismo que asignar a la clase misma:
226224

227225
```js
228226
MyClass.property = ...
229227
MyClass.method = ...
230228
```
231229

232-
Static properties and methods are inherited.
230+
Las propiedades y métodos estáticos se heredan.
233231

234-
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`.
232+
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)