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
The assignment to`Rabbit.prototype`sets up `[[Prototype]]`for new objects, but it does not affect the existing ones.
6
+
La asignación a`Rabbit.prototype`configura `[[Prototype]]`para objetos nuevos, pero no afecta a los existentes.
7
7
8
-
2.`false`.
8
+
2.`falso`.
9
9
10
-
Objects are assigned by reference. The object from`Rabbit.prototype`is not duplicated, it's still a single object referenced both by`Rabbit.prototype`and by the`[[Prototype]]`of`rabbit`.
10
+
Los objetos se asignan por referencia. El objeto de`Rabbit.prototype`no está duplicado, sigue siendo un solo objeto referenciado tanto por`Rabbit.prototype`como por el`[[Prototype]]`de`rabbit`.
11
11
12
-
So when we change its content through one reference, it is visible through the other one.
12
+
Entonces, cuando cambiamos su contenido a través de una referencia, es visible a través de la otra.
13
13
14
-
3.`true`.
14
+
3.`verdadero`.
15
15
16
-
All `delete`operations are applied directly to the object. Here`delete rabbit.eats`tries to remove `eats`property from `rabbit`, but it doesn't have it. So the operation won't have any effect.
16
+
Todas las operaciones `delete`se aplican directamente al objeto. Aquí`delete rabbit.eats`intenta eliminar la propiedad `eats`de `rabbit`, pero no la tiene. Entonces la operación no tendrá ningún efecto.
17
17
18
18
4.`undefined`.
19
19
20
-
The property`eats`is deleted from the prototype, it doesn't exist any more.
20
+
La propiedad`eats`se elimina del prototipo, ya no existe.
..But if someone, so to speak, overwrites`User.prototype`and forgets to recreate `constructor`to reference `User`, then it would fail.
18
+
..Pero si alguien, por así decirlo, sobrescribe`User.prototype`y olvida recrear `constructor`para hacer referencia a `User`, entonces fallaría.
19
19
20
-
For instance:
20
+
Por ejemplo:
21
21
22
22
```js run
23
23
functionUser(name) {
@@ -33,12 +33,12 @@ let user2 = new user.constructor('Pete');
33
33
alert( user2.name ); // undefined
34
34
```
35
35
36
-
Why `user2.name`is`undefined`?
36
+
¿Por qué `user2.name`es`undefined`?
37
37
38
-
Here's how `new user.constructor('Pete')` works:
38
+
Así es como funciona `new user.constructor('Pete')`:
39
39
40
-
1.First, it looks for `constructor`in`user`. Nothing.
41
-
2.Then it follows the prototype chain. The prototype of`user`is`User.prototype`, and it also has nothing.
42
-
3.The value of`User.prototype`is a plain object`{}`, its prototype is`Object.prototype`. And there is `Object.prototype.constructor == Object`. So it is used.
40
+
1.Primero, busca a `constructor`en`user`. Nada.
41
+
2.Luego sigue la cadena de prototipo. El prototipo de`user`es`User.prototype`, y tampoco tiene nada.
42
+
3.El valor de`User.prototype`es un objeto simple`{}`, su prototipo es`Object.prototype`. Y hay `Object.prototype.constructor == Object`. Entonces se usa.
43
43
44
44
At the end, we have `let user2 = new Object('Pete')`. The built-in `Object` constructor ignores arguments, it always creates an empty object, similar to `let user2 = {}`, that's what we have in `user2` after all.
Copy file name to clipboardExpand all lines: 1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
+4-4Lines changed: 4 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -2,14 +2,14 @@ importance: 5
2
2
3
3
---
4
4
5
-
# Create an object with the same constructor
5
+
# Crea un objeto con el mismo constructor
6
6
7
-
Imagine, we have an arbitrary object `obj`, created by a constructor function -- we don't know which one, but we'd like to create a new object using it.
7
+
Imagínese, tenemos un objeto arbitrario `obj`, creado por una función constructora; no sabemos cuál, pero nos gustaría crear un nuevo objeto con él.
8
8
9
-
Can we do it like that?
9
+
¿Podemos hacerlo así?
10
10
11
11
```js
12
12
let obj2 =newobj.constructor();
13
13
```
14
14
15
-
Give an example of a constructor function for`obj`which lets such code work right. And an example that makes it work wrong.
15
+
Dé un ejemplo de una función constructora para`obj`que permita que dicho código funcione correctamente. Y un ejemplo que hace que funcione mal.
Remember, new objects can be created with a constructor function, like`new F()`.
3
+
Recuerde, se pueden crear nuevos objetos con una función constructora, como`new F()`.
4
4
5
-
If`F.prototype`is an object, then the `new`operator uses it to set `[[Prototype]]`for the new object.
5
+
Si`F.prototype`es un objeto, entonces el operador `new`lo usa para establecer `[[Prototype]]`para el nuevo objeto.
6
6
7
7
```smart
8
-
JavaScript had prototypal inheritance from the beginning. It was one of the core features of the language.
8
+
JavaScript tenía herencia prototípica desde el principio. Era una de las características principales del lenguaje.
9
9
10
-
But in the old times, there was no direct access to it. The only thing that worked reliably was a `"prototype"` property of the constructor function, described in this chapter. So there are many scripts that still use it.
10
+
Pero en los viejos tiempos, no había acceso directo a él. Lo único que funcionó de manera confiable fue una propiedad `"prototype"` de la función constructora, descrita en este capítulo. Así que hay muchos scripts que todavía lo usan.
11
11
```
12
12
13
-
Please note that `F.prototype`here means a regular property named `"prototype"`on`F`. It sounds something similar to the term "prototype", but here we really mean a regular property with this name.
13
+
Tenga en cuenta que `F.prototype`aquí significa una propiedad regular llamada `"prototype"`en`F`. Suena algo similar al término "prototype", pero aquí realmente queremos decir una propiedad regular con este nombre.
14
14
15
-
Here's the example:
15
+
Aquí está el ejemplo:
16
16
17
17
```js run
18
18
let animal = {
@@ -27,95 +27,95 @@ function Rabbit(name) {
27
27
Rabbit.prototype= animal;
28
28
*/!*
29
29
30
-
let rabbit =newRabbit("White Rabbit"); // rabbit.__proto__ == animal
30
+
let rabbit =newRabbit("Conejo Blanco"); // rabbit.__proto__ == animal
31
31
32
-
alert( rabbit.eats ); //true
32
+
alert( rabbit.eats ); //verdadero
33
33
```
34
34
35
-
Setting `Rabbit.prototype = animal`literally states the following: "When a `new Rabbit` is created, assign its`[[Prototype]]`to`animal`".
35
+
La configuración de `Rabbit.prototype = animal`literalmente establece lo siguiente: "Cuando se crea un `new Rabbit`, asigne su`[[Prototype]]`a`animal`".
36
36
37
-
That's the resulting picture:
37
+
Esta es la imagen resultante:
38
38
39
39

40
40
41
-
On the picture, `"prototype"`is a horizontal arrow, meaning a regular property, and`[[Prototype]]`is vertical, meaning the inheritance of `rabbit`from`animal`.
41
+
En la imagen, `"prototype"`es una flecha horizontal, que significa una propiedad regular, y`[[Prototype]]`es vertical, que significa la herencia de `rabbit`desde`animal`.
42
42
43
-
```smart header="`F.prototype`only used at `new F` time"
44
-
`F.prototype`property is only used when `new F` is called, it assigns `[[Prototype]]`of the new object.
43
+
```smart header="`F.prototype`solo se usa en el momento `new F`"
44
+
La propiedad `F.prototype`solo se usa cuando se llama a `new F`, asigna `[[Prototype]]`del nuevo objeto.
45
45
46
-
If, after the creation, `F.prototype`property changes (`F.prototype = <another object>`), then new objects created by`new F`will have another object as `[[Prototype]]`, but already existing objects keep the old one.
46
+
Si, después de la creación, la propiedad `F.prototype`cambia (`F.prototype = <otro objeto>`), los nuevos objetos creados por`new F`tendrán otro objeto como `[[Prototype]]`, pero ya los objetos existentes conservan el antiguo.
47
47
```
48
48
49
-
## Default F.prototype, constructor property
49
+
## F.prototype predeterminado, propiedad del constructor
50
50
51
-
Every function has the `"prototype"` property even if we don't supply it.
51
+
Cada función tiene la propiedad `"prototype"` incluso si no la suministramos.
52
52
53
-
The default `"prototype"` is an object with the only property `constructor` that points back to the function itself.
53
+
El `"prototype"` predeterminado es un objeto con la única propiedad `constructor` que apunta de nuevo a la función misma.
We can use `constructor`property to create a new object using the same constructor as the existing one.
91
+
Podemos usar la propiedad `constructor`para crear un nuevo objeto usando el constructor ya existente.
92
92
93
-
Like here:
93
+
Como aqui:
94
94
95
95
```js run
96
96
functionRabbit(name) {
97
97
this.name= name;
98
98
alert(name);
99
99
}
100
100
101
-
let rabbit =newRabbit("White Rabbit");
101
+
let rabbit =newRabbit("Conejo Blanco");
102
102
103
103
*!*
104
-
let rabbit2 =newrabbit.constructor("Black Rabbit");
104
+
let rabbit2 =newrabbit.constructor("Conejo Negro");
105
105
*/!*
106
106
```
107
107
108
-
That's handy when we have an object, don't know which constructor was used for it (e.g. it comes from a 3rd party library), and we need to create another one of the same kind.
108
+
Eso es útil cuando tenemos un objeto, no sabemos qué constructor se usó para él (por ejemplo, proviene de una biblioteca de terceros), y necesitamos crear otro del mismo tipo.
109
109
110
-
But probably the most important thing about `"constructor"`is that...
110
+
Pero probablemente lo más importante sobre `"constructor"`es que ...
111
111
112
-
**...JavaScript itself does not ensure the right `"constructor"` value.**
112
+
**...JavaScript en sí mismo no garantiza el valor correcto de `"constructor"`.**
113
113
114
-
Yes, it exists in the default `"prototype"`for functions, but that's all. What happens with it later -- is totally on us.
114
+
Sí, existe en el `"prototipo"`predeterminado para las funciones, pero eso es todo. Lo que sucede con eso más tarde, depende totalmente de nosotros.
115
115
116
-
In particular, if we replace the default prototype as a whole, then there will be no `"constructor"`in it.
116
+
En particular, si reemplazamos el prototipo predeterminado como un todo, entonces no habrá `"constructor"`en él.
117
117
118
-
For instance:
118
+
Por ejemplo:
119
119
120
120
```js run
121
121
functionRabbit() {}
@@ -125,22 +125,22 @@ Rabbit.prototype = {
125
125
126
126
let rabbit =newRabbit();
127
127
*!*
128
-
alert(rabbit.constructor=== Rabbit); //false
128
+
alert(rabbit.constructor=== Rabbit); //falso
129
129
*/!*
130
130
```
131
131
132
-
So, to keep the right `"constructor"`we can choose to add/remove properties to the default `"prototype"`instead of overwriting it as a whole:
132
+
Entonces, para mantener el `"constructor"`correcto, podemos elegir agregar/eliminar propiedades al `"prototipo"`predeterminado en lugar de sobrescribirlo como un todo:
133
133
134
134
```js
135
135
functionRabbit() {}
136
136
137
-
//Not overwrite Rabbit.prototype totally
138
-
//just add to it
137
+
//No sobrescribir totalmente Rabbit.prototype
138
+
//solo agrégale
139
139
Rabbit.prototype.jumps=true
140
-
//the default Rabbit.prototype.constructor is preserved
140
+
//se conserva el Rabbit.prototype.constructor predeterminado
141
141
```
142
142
143
-
Or, alternatively, recreate the `constructor`property manually:
143
+
O, alternativamente, vuelva a crear la propiedad `constructor`manualmente:
144
144
145
145
```js
146
146
Rabbit.prototype= {
@@ -150,26 +150,26 @@ Rabbit.prototype = {
150
150
*/!*
151
151
};
152
152
153
-
//now constructor is also correct, because we added it
153
+
//ahora el constructor también es correcto, porque lo agregamos
154
154
```
155
155
156
156
157
-
## Summary
157
+
## Resumen
158
158
159
-
In this chapter we briefly described the way of setting a `[[Prototype]]` for objects created via a constructor function. Later we'll see more advanced programming patterns that rely on it.
159
+
En este capítulo describimos brevemente la forma de establecer un `[[Prototype]]` para los objetos creados a través de una función de constructor. Más adelante veremos patrones de programación más avanzados que dependen de él.
160
160
161
-
Everything is quite simple, just a few notes to make things clear:
161
+
Todo es bastante simple, solo algunas notas para aclarar las cosas:
162
162
163
-
- The `F.prototype` property (don't mistake it for `[[Prototype]]`) sets `[[Prototype]]` of new objects when `new F()` is called.
164
-
- The value of `F.prototype` should be either an object or `null`: other values won'twork.
165
-
-The`"prototype"`propertyonlyhassuchaspecialeffectwhensetonaconstructor function, and invoked with `new`.
163
+
- La propiedad `F.prototype` (nolaconfundacon`[[Prototype]]`) establece `[[Prototype]]` de objetos nuevos cuando se llama a `new F()`.
164
+
- El valor de `F.prototype` debe ser un objeto o `null`: otros valores no funcionarán.
165
+
- La propiedad `"prototype"` solo tiene un efecto tan especial cuando se establece en una función de constructor, y se invoca con `new`.
166
166
167
-
On regular objects the `prototype` is nothing special:
167
+
En los objetos normales, el `prototype` no es nada especial:
168
168
```js
169
169
let user = {
170
170
name:"John",
171
-
prototype: "Bla-bla" //no magic at all
171
+
prototype:"Bla-bla"//sin magia en absoluto
172
172
};
173
173
```
174
174
175
-
By default all functions have `F.prototype = {constructor: F}`, so we can get the constructor of an object by accessing its `"constructor"` property.
175
+
Por defecto, todas las funciones tienen `F.prototype= {constructor: F}`, por lo que podemos obtener el constructor de un objeto accediendo a su propiedad `"constructor"`.
0 commit comments