Skip to content

Commit cde00e0

Browse files
author
Maksumi Murakami
authored
Merge pull request #6 from javascript-tutorial/master
Update
2 parents d5ea01b + b613f50 commit cde00e0

File tree

2 files changed

+94
-83
lines changed

2 files changed

+94
-83
lines changed
Lines changed: 66 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
# Object copying, references
1+
# Copia de objetos, referencias
22

3-
One of the fundamental differences of objects vs primitives is that they are stored and copied "by reference".
3+
Una de las diferencias fundamentales de los objetos respecto a los primitivos es que son almacenados y copiados "por referencia".
44

5-
Primitive values: strings, numbers, booleans -- are assigned/copied "as a whole value".
5+
Los valores primitivos: strings, numbers, booleans -- son asignados y copiados "como un valor completo".
66

7-
For instance:
7+
Por ejemplo:
88

99
```js
1010
let message = "Hello!";
1111
let phrase = message;
1212
```
1313

14-
As a result we have two independent variables, each one is storing the string `"Hello!"`.
14+
Como resultado tenemos dos variables independientes, cada una almacenando la cadena `"Hello!"`.
1515

1616
![](variable-copy-value.svg)
1717

18-
Objects are not like that.
18+
Los objetos no son así.
1919

20-
**A variable stores not the object itself, but its "address in memory", in other words "a reference" to it.**
20+
**Una variable no almacena el objeto mismo sino su "dirección en memoria", en otras palabras "una referencia" a él.**
2121

22-
Here's the picture for the object:
22+
Aquí tenemos una imagen del objeto:
2323

2424
```js
2525
let user = {
@@ -29,76 +29,76 @@ let user = {
2929

3030
![](variable-contains-reference.svg)
3131

32-
Here, the object is stored somewhere in memory. And the variable `user` has a "reference" to it.
32+
Aquí, el objeto es almacenado en algún lugar de la memoria. Y la variable `user` tiene una "referencia" a él.
3333

34-
**When an object variable is copied -- the reference is copied, the object is not duplicated.**
34+
**Cuando una variable de objeto es copiada -- la referencia es copiada, el objeto no es duplicado.**
3535

36-
For instance:
36+
Por ejemplo:
3737

3838
```js no-beautify
3939
let user = { name: "John" };
4040

41-
let admin = user; // copy the reference
41+
let admin = user; // copia la referencia
4242
```
4343

44-
Now we have two variables, each one with the reference to the same object:
44+
Ahora tenemos dos variables, cada una con una referencia al mismo objeto:
4545

4646
![](variable-copy-reference.svg)
4747

48-
We can use any variable to access the object and modify its contents:
48+
Podemos usar cualquiera de las variables para acceder al objeto y modificar su contenido:
4949

5050
```js run
5151
let user = { name: 'John' };
5252

5353
let admin = user;
5454

5555
*!*
56-
admin.name = 'Pete'; // changed by the "admin" reference
56+
admin.name = 'Pete'; // cambiado por la referencia "admin"
5757
*/!*
5858

59-
alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference
59+
alert(*!*user.name*/!*); // 'Pete', los cambios se ven desde la referencia "user"
6060
```
6161
62-
The example above demonstrates that there is only one object. As if we had a cabinet with two keys and used one of them (`admin`) to get into it. Then, if we later use another key (`user`) we can see changes.
62+
El ejemplo anterior demuestra que solamente hay un único objeto. Como si tuviéramos un gabinete con dos llaves y usáramos una de ellas (`admin`) para accederlo. Si más tarde usamos la llave (`user`), podemos ver los cambios.
6363
64-
## Comparison by reference
64+
## Comparación por referencia
6565
66-
The equality `==` and strict equality `===` operators for objects work exactly the same.
66+
En los objetos, los operadores de igualdad `==` e igualdad estricta `===` funcionan exactamente igual.
6767
68-
**Two objects are equal only if they are the same object.**
68+
**Dos objetos son iguales solamente si ellos son el mismo objeto.**
6969
70-
Here two variables reference the same object, thus they are equal:
70+
Aquí dos variables referencian el mismo objeto, así que ellos son iguales:
7171
7272
```js run
7373
let a = {};
74-
let b = a; // copy the reference
74+
let b = a; // copia la referencia
7575

76-
alert( a == b ); // true, both variables reference the same object
76+
alert( a == b ); // true, verdadero. Ambas variables hacen referencia al mismo objeto
7777
alert( a === b ); // true
7878
```
7979
80-
And here two independent objects are not equal, even though both are empty:
80+
Y aquí dos objetos independientes no son iguales, incluso estando ambos vacíos:
8181
8282
```js run
8383
let a = {};
84-
let b = {}; // two independent objects
84+
let b = {}; // dos objetos independientes
8585

8686
alert( a == b ); // false
8787
```
8888
89-
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons occur very rarely, usually as a result of a coding mistake.
89+
Para comparaciones como `obj1 > obj2`, o comparaciones contra un primitivo `obj == 5`, los objetos son convertidos a primitivos. Estudiaremos cómo funciona la conversión de objetos pronto, pero a decir verdad tales comparaciones ocurren raramente y suelen ser errores de código.
9090
91-
## Cloning and merging, Object.assign
91+
## Clonación y mezcla, Object.assign
9292
93-
So, copying an object variable creates one more reference to the same object.
93+
Entonces copiar una variable de objeto crea una referencia adicional al mismo objeto.
9494
95-
But what if we need to duplicate an object? Create an independent copy, a clone?
95+
Pero ¿si necesitamos duplicar un objeto? ¿Crear una copia independiente, un clon?
9696
97-
That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. Actually, that's rarely needed. Copying by reference is good most of the time.
97+
Eso también es factible, pero un poco más difícil porque no hay un método incorporado para eso en JavaScript. En realidad, eso es raramente necesario. Copiar por referencia está bien la mayoría de las veces.
9898
99-
But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level.
99+
Pero si realmente queremos eso, necesitamos crear un nuevo objeto y replicar la estructura del existente iterando a través de sus propiedades y copiándolas en el nivel primitivo.
100100
101-
Like this:
101+
Como esto:
102102
103103
```js run
104104
let user = {
@@ -107,59 +107,59 @@ let user = {
107107
};
108108

109109
*!*
110-
let clone = {}; // the new empty object
110+
let clone = {}; // el nuevo objeto vacío
111111

112-
// let's copy all user properties into it
112+
// copiemos todas las propiedades de user en él
113113
for (let key in user) {
114114
clone[key] = user[key];
115115
}
116116
*/!*
117117

118-
// now clone is a fully independent object with the same content
119-
clone.name = "Pete"; // changed the data in it
118+
// ahora clone es un objeto totalmente independiente con el mismo contenido
119+
clone.name = "Pete"; // cambiamos datos en él
120120

121-
alert( user.name ); // still John in the original object
121+
alert( user.name ); // John aún está en el objeto original
122122
```
123123
124-
Also we can use the method [Object.assign](mdn:js/Object/assign) for that.
124+
También podemos usar el método [Object.assign](mdn:js/Object/assign) para ello.
125125
126-
The syntax is:
126+
La sintaxis es:
127127
128128
```js
129129
Object.assign(dest, [src1, src2, src3...])
130130
```
131131
132-
- The first argument `dest` is a target object.
133-
- Further arguments `src1, ..., srcN` (can be as many as needed) are source objects.
134-
- It copies the properties of all source objects `src1, ..., srcN` into the target `dest`. In other words, properties of all arguments starting from the second are copied into the first object.
135-
- The call returns `dest`.
132+
- El primer argumento `dest` es el objeto destinatario.
133+
- Los siguientes argumentos `src1, ..., srcN` (tantos como sea necesario) son objetos fuentes.
134+
- Esto copia todas las propiedades de todos los objetos fuentes `src1, ..., srcN` dentro del destino `dest`. En otras palabras, las propiedades de todos los argumentos, comenzando desde el segundo, son copiadas en el primer objeto.
135+
- El llamado devuelve `dest`.
136136
137-
For instance, we can use it to merge several objects into one:
137+
Por ejemplo, podemos usarlo para combinar distintos objetos en uno:
138138
```js
139139
let user = { name: "John" };
140140

141141
let permissions1 = { canView: true };
142142
let permissions2 = { canEdit: true };
143143

144144
*!*
145-
// copies all properties from permissions1 and permissions2 into user
145+
// copia todas las propiedades desde permissions1 y permissions2 en user
146146
Object.assign(user, permissions1, permissions2);
147147
*/!*
148148

149-
// now user = { name: "John", canView: true, canEdit: true }
149+
// ahora user = { name: "John", canView: true, canEdit: true }
150150
```
151151
152-
If the copied property name already exists, it gets overwritten:
152+
Si la propiedad por copiar ya existe, se sobrescribe:
153153
154154
```js run
155155
let user = { name: "John" };
156156

157157
Object.assign(user, { name: "Pete" });
158158

159-
alert(user.name); // now user = { name: "Pete" }
159+
alert(user.name); // ahora user = { name: "Pete" }
160160
```
161161
162-
We also can use `Object.assign` to replace `for..in` loop for simple cloning:
162+
También podemos usar `Object.assign` reemplazando el bucle `for..in` para hacer una clonación simple:
163163
164164
```js
165165
let user = {
@@ -172,13 +172,13 @@ let clone = Object.assign({}, user);
172172
*/!*
173173
```
174174
175-
It copies all properties of `user` into the empty object and returns it.
175+
Copia todas las propiedades de `user` en un objeto vacío y lo devuelve.
176176
177-
## Nested cloning
177+
## Clonación anidada
178178
179-
Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them?
179+
Hasta ahora asumimos que todas las propiedades de `user` son primitivas. Pero las propiedades pueden ser referencias a otros objetos. ¿Qué hacer con ellas?
180180
181-
Like this:
181+
Como esto:
182182
```js run
183183
let user = {
184184
name: "John",
@@ -191,9 +191,9 @@ let user = {
191191
alert( user.sizes.height ); // 182
192192
```
193193
194-
Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes:
194+
Ahora no es suficiente copiar `clone.sizes = user.sizes`, porque `user.sizes` es un objeto y será copiado por referencia. Entonces `clone` y `user` compartirán las mismas tallas (.sizes):
195195
196-
Like this:
196+
Como esto:
197197
198198
```js run
199199
let user = {
@@ -206,23 +206,23 @@ let user = {
206206

207207
let clone = Object.assign({}, user);
208208

209-
alert( user.sizes === clone.sizes ); // true, same object
209+
alert( user.sizes === clone.sizes ); // true, el mimo objeto
210210

211-
// user and clone share sizes
212-
user.sizes.width++; // change a property from one place
213-
alert(clone.sizes.width); // 51, see the result from the other one
211+
// user y clone comparten sizes
212+
user.sizes.width++; // cambia la propiedad en un lugar
213+
alert(clone.sizes.width); // 51, ve el resultado desde el otro
214214
```
215215
216-
To fix that, we should use the cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
216+
Para corregir esto, debemos usar un bucle de clonación que examine cada valor de `user[key]` y, si es un objeto, replicar su estructura también. Esto es llamado "clonación profunda".
217217
218-
There's a standard algorithm for deep cloning that handles the case above and more complex cases, called the [Structured cloning algorithm](https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data).
218+
Hay un algoritmo estándar para clonación profunda que maneja este caso y otros más complicados llamado [Structured cloning algorithm](https://html.spec.whatwg.org/multipage/structured-data.html#safe-passing-of-structured-data).
219219
220-
We can use recursion to implement it. Or, not to reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
220+
Podemos usar recursividad para implementarlo. O, para no inventar la rueda, tomar una implementación existente, por ejemplo [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) de la librería JavaScript [lodash](https://lodash.com).
221221
222-
## Summary
222+
## Resumen
223223
224-
Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object.
224+
Los objetos son asignados y copiados por referencia. En otras palabras, una variable almacena no el valor del objeto sino una referencia (dirección de memoria) del valor. Entoncess copiar tal variable o pasarla como argumento de función copia la referencia, no el objeto.
225225
226-
All operations via copied references (like adding/removing properties) are performed on the same single object.
226+
Todas la operaciones a través de referencias copiadas (como agregar y borrar propiedades) son efectuadas en el mismo y único objeto .
227227
228-
To make a "real copy" (a clone) we can use `Object.assign` for the so-called "shallow copy" (nested objects are copied by reference) or a "deep cloning" function, such as [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).
228+
Si queremos conseguir una "copia real" (un clon), podemos usar: Una "clonación superficial" por medio de la función `Object.assign` (con los objetos anidados copiados por referencia), o una "clonación profunda" con una función como [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).

1-js/06-advanced-functions/04-var/article.md

Lines changed: 28 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,27 +13,18 @@ In the very first chapter about [variables](info:variables), we mentioned three
1313
2. `const`
1414
3. `var`
1515

16-
`let` and `const` behave exactly the same way in terms of Lexical Environments.
17-
18-
But `var` is a very different beast, that originates from very old times. It's generally not used in modern scripts, but still lurks in the old ones.
19-
20-
If you don't plan on meeting such scripts you may even skip this chapter or postpone it, but then there's a chance that it bites you later.
21-
22-
From the first sight, `var` behaves similar to `let`. That is, declares a variable:
16+
The `var` declaration is similar to `let`. Most of the time we can replace `let` by `var` or vice-versa and expect things to work:
2317

2418
```js run
25-
function sayHi() {
26-
var phrase = "Hello"; // local variable, "var" instead of "let"
27-
28-
alert(phrase); // Hello
29-
}
19+
var message = "Hi";
20+
alert(message); // Hi
21+
```
3022

31-
sayHi();
23+
But internally `var` is a very different beast, that originates from very old times. It's generally not used in modern scripts, but still lurks in the old ones.
3224

33-
alert(phrase); // Error, phrase is not defined
34-
```
25+
If you don't plan on meeting such scripts you may even skip this chapter or postpone it.
3526

36-
...But here are the differences.
27+
On the other hand, it's important to understand differences when migrating old scripts from `var` to `let`, to avoid odd errors.
3728

3829
## "var" has no block scope
3930

@@ -94,7 +85,27 @@ alert(phrase); // Error: phrase is not defined (Check the Developer Console)
9485

9586
As we can see, `var` pierces through `if`, `for` or other code blocks. That's because a long time ago in JavaScript blocks had no Lexical Environments. And `var` is a remnant of that.
9687

97-
## "var" declarations are processed at the function start
88+
## "var" tolerates redeclarations
89+
90+
If we declare the same variable with `let` twice in the same scope, that's an error:
91+
92+
```js run
93+
let user;
94+
let user; // SyntaxError: 'user' has already been declared
95+
```
96+
97+
With `var`, we can redeclare a variable any number of times. If we use `var` with an already-declared variable, it's just ignored:
98+
99+
```js run
100+
var user = "Pete";
101+
102+
var user = "John"; // this "var" does nothing (already declared)
103+
// ...it doesn't trigger an error
104+
105+
alert(user); // John
106+
```
107+
108+
## "var" variables can be declared below their use
98109

99110
`var` declarations are processed when the function starts (or script starts for globals).
100111

0 commit comments

Comments
 (0)