You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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*.
5
5
6
-
An example:
6
+
En una clase, están precedidos por la palabra clave `static`, como esta:
7
7
8
8
```js run
9
9
classUser {
@@ -14,24 +14,26 @@ class User {
14
14
}
15
15
}
16
16
17
-
User.staticMethod(); //true
17
+
User.staticMethod(); //verdadero
18
18
```
19
19
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:
21
21
22
-
```js
23
-
functionUser() { }
22
+
```js run
23
+
classUser { }
24
24
25
25
User.staticMethod=function() {
26
26
alert(this=== User);
27
27
};
28
+
29
+
User.staticMethod(); // verdadero
28
30
```
29
31
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").
31
33
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.
33
35
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:
35
37
36
38
```js run
37
39
classArticle {
@@ -47,31 +49,31 @@ class Article {
47
49
*/!*
48
50
}
49
51
50
-
//usage
52
+
//uso
51
53
let articles = [
52
-
newArticle("Mind", newDate(2019, 1, 1)),
53
-
newArticle("Body", newDate(2019, 0, 1)),
54
+
newArticle("HTML", newDate(2019, 1, 1)),
55
+
newArticle("CSS", newDate(2019, 0, 1)),
54
56
newArticle("JavaScript", newDate(2019, 11, 1))
55
57
];
56
58
57
59
*!*
58
60
articles.sort(Article.compare);
59
61
*/!*
60
62
61
-
alert( articles[0].title ); //Body
63
+
alert( articles[0].title ); //CSS
62
64
```
63
65
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.
65
67
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:
67
69
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.
71
73
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.
73
75
74
-
Like `Article.createTodays()`here:
76
+
Al igual que `Article.createTodays()`aquí:
75
77
76
78
```js run
77
79
classArticle {
@@ -82,32 +84,32 @@ class Article {
82
84
83
85
*!*
84
86
staticcreateTodays() {
85
-
//remember, this = Article
86
-
returnnewthis("Today's digest", newDate());
87
+
//recuerda, this = Article
88
+
returnnewthis("Resumen de hoy", newDate());
87
89
}
88
90
*/!*
89
91
}
90
92
91
93
let article =Article.createTodays();
92
94
93
-
alert( article.title ); //Todays digest
95
+
alert( article.title ); //Resumen de hoy
94
96
```
95
97
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.
97
99
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:
99
101
100
102
```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:
103
105
Article.remove({id:12345});
104
106
```
105
107
106
-
## Static properties
108
+
## Propiedades estáticas
107
109
108
110
[recent browser=Chrome]
109
111
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`:
111
113
112
114
```js run
113
115
classArticle {
@@ -117,20 +119,21 @@ class Article {
117
119
alert( Article.publisher ); // Ilya Kantor
118
120
```
119
121
120
-
That is the same as a direct assignment to`Article`:
122
+
Eso es lo mismo que una asignación directa a`Article`:
121
123
122
124
```js
123
125
Article.publisher="Ilya Kantor";
124
126
```
125
127
126
-
## Statics and inheritance
128
+
## Herencia de propiedades y métodos estáticos.
127
129
128
-
Statics are inherited, we can access `Parent.method` as `Child.method`.
130
+
Las propiedades y métodos estáticos son heredados.
129
131
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`:
131
133
132
134
```js run
133
135
classAnimal {
136
+
static planet ="Tierra";
134
137
135
138
constructor(name, speed) {
136
139
this.speed= speed;
@@ -139,7 +142,7 @@ class Animal {
139
142
140
143
run(speed=0) {
141
144
this.speed+= speed;
142
-
alert(`${this.name}runs with speed${this.speed}.`);
145
+
alert(`${this.name}corre a una velocidad de${this.speed}.`);
143
146
}
144
147
145
148
*!*
@@ -150,59 +153,64 @@ class Animal {
150
153
151
154
}
152
155
153
-
//Inherit from Animal
156
+
//Hereda de Animal
154
157
classRabbitextendsAnimal {
155
158
hide() {
156
-
alert(`${this.name}hides!`);
159
+
alert(`${this.name}se esconde!`);
157
160
}
158
161
}
159
162
160
163
let rabbits = [
161
-
newRabbit("White Rabbit", 10),
162
-
newRabbit("Black Rabbit", 5)
164
+
newRabbit("Conejo Blanco", 10),
165
+
newRabbit("Conejo Negro", 5)
163
166
];
164
167
165
168
*!*
166
169
rabbits.sort(Rabbit.compare);
167
170
*/!*
168
171
169
-
rabbits[0].run(); // Black Rabbit runs with speed 5.
170
-
```
172
+
rabbits[0].run(); // Conejo Negro corre a una velocidad de 5.
171
173
172
-
Now we can call `Rabbit.compare` assuming that the inherited `Animal.compare` will be called.
174
+
alert(Rabbit.planet); // Tierra
175
+
```
173
176
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.
175
178
179
+
¿Como funciona? Nuevamente, usando prototipos. Como ya habrás adivinado, `extends` da a `Rabbit` el `[[Prototype]]` referente a `Animal`.
176
180
177
181

178
182
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]]`:
180
184
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.
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.
198
206
199
-
## Summary
207
+
Por ejemplo, un método para comparar `Article.compare (article1, article2)` o un método de fábrica `Article.createTodays()`.
200
208
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.
202
210
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.
204
212
205
-
The syntax is:
213
+
La sintaxis es:
206
214
207
215
```js
208
216
classMyClass {
@@ -214,13 +222,13 @@ class MyClass {
214
222
}
215
223
```
216
224
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:
218
226
219
227
```js
220
228
MyClass.property=...
221
229
MyClass.method=...
222
230
```
223
231
224
-
Static properties are inherited.
232
+
Las propiedades y métodos estáticos se heredan.
225
233
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