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
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects.
3
+
JavaScript nos permite trabajar con datos primitivos (strings, numbers, etc.) como si fueran objetos.
4
4
5
-
They also provide methods to call as such. We will study those soon, but first we'll see how it works because, of course, primitives are not objects (and here we will make it even clearer).
5
+
También proveen, como aquellos, métodos para ser llamados. Los estudiaremos pronto, pero primero veamos cómo trabajan porque, por supuesto, los primitivos no son objetos (y aquí lo haremos más evidente).
6
6
7
-
Let's look at the key distinctions between primitives and objects.
7
+
Veamos las diferencias clave entre primitivos y objetos.
8
8
9
-
A primitive
9
+
Un primitivo
10
10
11
-
-Is a value of a primitive type.
12
-
-There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null`and`undefined`.
-Is capable of storing multiple values as properties.
17
-
-Can be created with`{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript; functions, for example, are objects.
16
+
-Es capaz de almacenar múltiples valores como propiedades.
17
+
-Puede ser creado con`{}`, por ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; por ejemplo, las funciones (`function`) son objetos .
18
18
19
-
One of the best things about objects is that we can store a function as one of its properties.
19
+
Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades.
20
20
21
21
```js run
22
22
let john = {
@@ -29,102 +29,102 @@ let john = {
29
29
john.sayHi(); // Hi buddy!
30
30
```
31
31
32
-
So here we've made an object `john`with the method`sayHi`.
32
+
Aquí hemos hecho un función `john`con el método`sayHi` (saludar).
33
33
34
-
Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods.
34
+
Ya existen muchos objetos incorporados, como aquellos que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos.
35
35
36
-
But, these features come with a cost!
36
+
¡Pero estas características vienen con un costo!
37
37
38
-
Objects are "heavier" than primitives. They require additional resources to support the internal machinery. But as properties and methods are very useful in programming, JavaScript engines try to optimize them to reduce the additional burden.
38
+
Los objetos son más "pesados" que los primitivos. Requieren recursos adicionales para soportar su maquinaria interna. Pero como las propiedades y los métodos son tan útiles en programación, los motores JavaScript tratan de optimizarlos para reducir su carga adiional.
39
39
40
-
## A primitive as an object
40
+
## Un primitivo como objeto
41
41
42
-
Here's the paradox faced by the creator of JavaScript:
42
+
Aquí la paradoja que enfrentó el creador de JavaScript:
43
43
44
-
-There are many things one would want to do with a primitive like a string or a number. It would be great to access them as methods.
45
-
-Primitives must be as fast and lightweight as possible.
44
+
-Hay muchas cosas que uno quisiera hacer con primitivos como string o number. Sería grandioso acceder a métodos.
45
+
-Los Primitivos deben ser tan rápidos y livianos como sea posible.
46
46
47
-
The solution looks a little bit awkward, but here it is:
47
+
La solución se ve algo enrevesada, pero aquí está:
48
48
49
-
1.Primitives are still primitive. A single value, as desired.
50
-
2.The language allows access to methods and properties of strings, numbers, booleans and symbols.
51
-
3.When this happens, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
49
+
1.Los primitivos son aún primitivos. Con un valor único, como es deseable.
50
+
2.El lenguaje permite acceder a métodos y propiedades de strings, numbers, booleans y symbols.
51
+
3.Cuando esto ocurre, un "object wrapper" (objeto envoltura) especial que provee la funcionalidad extra es creado y luego destruido.
52
52
53
-
The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean`and`Symbol`. Thus, they provide different sets of methods.
53
+
Los "object wrappers" son diferentes para cada tipo primitivo y son llamados: `String`, `Number`, `Boolean`y`Symbol`. Así proveen diferentes sets de métodos.
54
54
55
-
For instance, there exists a method [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)that returns a capitalized string.
55
+
Por ejemplo, hay un método [str.toUpperCase()](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/toUpperCase)que devuelve un string en mayúsculas.
56
56
57
-
Here's how it works:
57
+
Aquí cómo funciona:
58
58
59
59
```js run
60
60
let str ="Hello";
61
61
62
62
alert( str.toUpperCase() ); // HELLO
63
63
```
64
64
65
-
Simple, right? Here's what actually happens in`str.toUpperCase()`:
65
+
Simple, ¿no es así? Lo que realmente ocurre en`str.toUpperCase()`:
66
66
67
-
1.The string `str`is a primitive. So in the moment of accessing its property, a special object is created that knows the value of the string, and has useful methods, like`toUpperCase()`.
68
-
2.That method runs and returns a new string (shown by`alert`).
69
-
3.The special object is destroyed, leaving the primitive `str` alone.
67
+
1.El string `str`es un tipo primitivo. Entonces al momento de acceder a su propiedad, un objeto especial es creado, uno que conoce el valor del string y tiene métodos útiles como`toUpperCase()`.
68
+
2.El método se ejecuta y devuelve un nuevo string (el mostrado con`alert`).
69
+
3.El objeto especial es destruido, dejando solo el primitivo `str`.
70
70
71
-
So primitives can provide methods, but they still remain lightweight.
71
+
Así las primitivas pueden proveer métodos y aún permanecer livianas.
72
72
73
-
The JavaScript engine highly optimizes this process. It may even skip the creation of the extra object at all. But it must still adhere to the specification and behave as if it creates one.
73
+
El motor JavaScript optimiza este proceso enormemente. Puede incluso saltear la creación del objeto extra por completo. Pero aún debe adherir a la especificación y comportarse como si creara uno.
74
74
75
-
A number has methods of its own, for instance,[toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)rounds the number to the given precision:
75
+
Un number tiene sus propios métodos, por ejemplo[toFixed(n)](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/toFixed)redondea el número a la precisión dada:
76
76
77
77
```js run
78
78
let n =1.23456;
79
79
80
80
alert( n.toFixed(2) ); // 1.23
81
81
```
82
82
83
-
We'll see more specific methods in chapters<info:number>and<info:string>.
83
+
Veremos más métodos específicos en los capítulos<info:number>y<info:string>.
84
84
85
85
86
-
````warn header="Constructors `String/Number/Boolean`are for internal use only"
87
-
Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like`new Number(1)`or`new Boolean(false)`.
86
+
````warn header="Constructors `String/Number/Boolean`son de uso interno solamente"
87
+
Algunos lenguajes como JAva permiten crear "wrapper objects" para primitivas explícitamente usando una sintaxis como`new Number(1)`o`new Boolean(false)`.
88
88
89
-
In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places.
89
+
En JavaScript, eso también es posible por razones históricas, pero firmemente **no recomendado**. Las cosas enloquecerán en varios lugares.
90
90
91
-
For instance:
91
+
Por ejemplo:
92
92
93
93
```js run
94
94
alert( typeof1 ); // "number"
95
95
96
96
alert( typeofnewNumber(1) ); // "object"!
97
97
```
98
98
99
-
And because what follows, `zero`, is an object, the alert will show up:
99
+
Los objetos son siempre verdaderos en un if, por ello el alert se mostrará:
100
100
101
101
```js run
102
102
let zero =newNumber(0);
103
103
104
-
if (zero) { // zero is true, because it's an object
105
-
alert( "zero is truthy?!?" );
104
+
if (zero) { // zero es true, porque es un objeto
105
+
alert( "zero es verdadero?!?" );
106
106
}
107
107
```
108
108
109
-
On the other hand, using the same functions`String/Number/Boolean`without`new`is a totally sane and useful thing. They convert a value to the corresponding type: to a string, a number, or a boolean (primitive).
109
+
Por otro lado, usar las mismas funciones`String/Number/Boolean`sin`new`es totalmente sano y útil. Ellos convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo).
110
110
111
-
For example, this is entirely valid:
111
+
Por ejemplo, esto es perfectamente válido:
112
112
```js
113
-
let num =Number("123"); //convert a string to number
113
+
let num =Number("123"); //convierte string a number
114
114
```
115
115
````
116
116
117
117
118
118
````warn header="null/undefined have no methods"
119
-
The special primitives `null` and `undefined` are exceptions. They have no corresponding "wrapper objects" and provide no methods. In a sense, they are "the most primitive".
119
+
Las primitivas especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo".
120
120
121
-
An attempt to access a property of such value would give the error:
121
+
El intento de acceder a una propiedad de tal valor daría error:
122
122
123
123
```js run
124
124
alert(null.test); // error
125
125
````
126
126
127
-
## Summary
127
+
## Resumen
128
128
129
-
-Primitives except `null`and`undefined`provide many helpful methods. We will study those in the upcoming chapters.
130
-
-Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.
129
+
-Las primitivas excepto `null`y`undefined`proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos.
130
+
-Formalmente, estos métodos trabajan a través de objetos temporales, pero los motores de JavaScript están bien afinados para optimizarlos internamente, así que llamarlos no es costoso.
0 commit comments