Skip to content

Commit 243f044

Browse files
authored
Merge pull request #199 from joaquinelio/primitives-methods
Methods of primitives Desacuerdo con la definición llamada "wrapper", pero ahora el nuevo glosario me lo permite. Si se redefine, siempre se pude hacer un PR... cuando terminemos los más de 100 artículos.
2 parents 2175e08 + ee4c625 commit 243f044

File tree

3 files changed

+63
-63
lines changed

3 files changed

+63
-63
lines changed
Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
Try running it:
2+
Prueba ejecutándolo:
33

44
```js run
55
let str ="Hello";
@@ -9,16 +9,16 @@ str.test = 5; // (*)
99
alert(str.test);
1010
```
1111

12-
Depending on whether you have `use strict` or not, the result may be:
13-
1.`undefined` (no strict mode)
14-
2.An error(strict mode).
12+
Depende de si usas el modo estricto "use strict" o no, el resultado será:
13+
1.`undefined` (sin strict mode)
14+
2.Un error. (strict mode)
1515

16-
Why? Let's replay what's happening at line`(*)`:
16+
¿Por qué? Repasemos lo que ocurre en la línea`(*)`:
1717

18-
1.When a property of `str` is accessed, a "wrapper object" is created.
19-
2.In strict mode, writing into it is an error.
20-
3.Otherwise, the operation with the property is carried on, the object gets the`test` property, but after that the "wrapper object" disappears, so in the last line`str`has no trace of the property.
18+
1.Cuando se accede a una propiedad de `str`, se crea un "wrapper object" (objeto envolvente ).
19+
2.Con modo estricto, tratar de alterarlo produce error.
20+
3.Sin modo estricto, la operación es llevada a cabo y el objeto obtiene la propiedad`test`, pero después de ello el "objeto envolvente" desaparece, entonces en la última linea`str`queda sin rastros de la propiedad.
2121

22-
**This example clearly shows that primitives are not objects.**
22+
**Este ejemlplo claramente muestra que los tipos primitivos no son objetos.**
2323

24-
They can't store additional data.
24+
Ellos no pueden almacenar datos adicionales.

‎1-js/05-data-types/01-primitives-methods/1-string-new-property/task.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ importance: 5
22

33
---
44

5-
# Can I add a string property?
5+
# ¿Puedo agregar una propiedad a un string?
66

77

8-
Consider the following code:
8+
Considera el siguiente código:
99

1010
```js
1111
let str ="Hello";
@@ -15,4 +15,4 @@ str.test = 5;
1515
alert(str.test);
1616
```
1717

18-
How do you think, will it work? What will be shown?
18+
Qué piensas, ¿funcionará? ¿Que mostrará?
Lines changed: 50 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
1-
# Methods of primitives
1+
# Métodos en tipos primitivos
22

3-
JavaScript allows us to work with primitives (strings, numbers, etc.) as if they were objects. 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).
3+
JavaScript nos permite trabajar con tipos de datos primitivos (string, number, etc) como si fueran objetos. Los primitivos también brindan 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 aún más evidente).
44

5-
Let's look at the key distinctions between primitives and objects.
5+
Veamos las diferencias clave entre primitivos y objetos.
66

7-
A primitive
7+
Un primitivo
88

9-
-Is a value of a primitive type.
10-
-There are 7 primitive types: `string`, `number`, `bigint`, `boolean`, `symbol`, `null`and`undefined`.
9+
-Es un valor de tipo primitivo.
10+
-Hay 7 tipos primitivos: `string`, `number`, `bigint`, `boolean`, `symbol`, `null`y`undefined`.
1111

12-
An object
12+
Un objeto
1313

14-
-Is capable of storing multiple values as properties.
15-
-Can be created with`{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript: functions, for example, are objects.
14+
-Es capaz de almacenar múltiples valores como propiedades.
15+
-Puede ser creado con`{}`. Ejemplo: `{name: "John", age: 30}`. Hay otras clases de objetos en JavaScript; las funciones, por ejemplo, son objetos.
1616

17-
One of the best things about objects is that we can store a function as one of its properties.
17+
Una de las mejores cosas de los objetos es que podemos almacenar una función como una de sus propiedades.
1818

1919
```js run
2020
let john ={
@@ -27,102 +27,102 @@ let john ={
2727
john.sayHi(); // Hi buddy!
2828
```
2929

30-
So here we've made an object `john`with the method`sayHi`.
30+
Aquí hemos creado un objeto `john`con el método`sayHi`.
3131

32-
Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods.
32+
Ya existen muchos objetos integrados al lenguaje, como los que trabajan con fechas, errores, elementos HTML, etc. Ellos tienen diferentes propiedades y métodos.
3333

34-
But, these features come with a cost!
34+
¡Pero estas características tienen un precio!
3535

36-
Objects are "heavier" than primitives. They require additional resources to support the internal machinery.
36+
Los objetos son más "pesados" que los primitivos. Ellos requieren recursos adicionales para soportar su maquinaria interna.
3737

38-
## A primitive as an object
38+
## Un primitivo como objeto
3939

40-
Here's the paradox faced by the creator of JavaScript:
40+
Aquí el dilema que enfrentó el creador de JavaScript:
4141

42-
-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.
43-
-Primitives must be as fast and lightweight as possible.
42+
-Hay muchas cosas que uno querría hacer con los primitivos como string o number. Sería grandioso accederlas como métodos.
43+
-Los Primitivos deben ser tan rápidos y livianos como sea posible
4444

45-
The solution looks a little bit awkward, but here it is:
45+
La solución es algo enrevesada, pero aquí está:
4646

47-
1.Primitives are still primitive. A single value, as desired.
48-
2.The language allows access to methods and properties of strings, numbers, booleans and symbols.
49-
3.In order for that to work, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
47+
1.Los primitivos son aún primitivos. Con un valor único, como es deseable.
48+
2.El lenguaje permite el acceso a métodos y propiedades de strings, numbers, booleans y symbols.
49+
3.Para que esto funcione, se crea una envoltura especial, un "object wrapper" (objeto envoltorio) que provee la funcionalidad extra y luego es destruido.
5050

51-
The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean`and`Symbol`. Thus, they provide different sets of methods.
51+
Los "object wrappers" son diferentes para cada primitivo y son llamados: `String`, `Number`, `Boolean`y`Symbol`. Así, proveen diferentes sets de métodos.
5252

53-
For instance, there exists a string method [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase)that returns a capitalized `str`.
53+
Por ejemplo, existe 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.
5454

55-
Here's how it works:
55+
Aquí el funcionamiento:
5656

5757
```js run
5858
let str ="Hello";
5959

6060
alert( str.toUpperCase() ); // HELLO
6161
```
6262

63-
Simple, right? Here's what actually happens in`str.toUpperCase()`:
63+
Simple, ¿no es así? Lo que realmente ocurre en`str.toUpperCase()`:
6464

65-
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()`.
66-
2.That method runs and returns a new string (shown by`alert`).
67-
3.The special object is destroyed, leaving the primitive `str` alone.
65+
1.El string `str`es primitivo. 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()`.
66+
2.Ese método se ejecuta y devuelve un nuevo string (mostrado con`alert`).
67+
3.El objeto especial es destruido, dejando solo el primitivo `str`.
6868

69-
So primitives can provide methods, but they still remain lightweight.
69+
Así los primitivos pueden proveer métodos y aún permanecer livianos.
7070

71-
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.
71+
El motor JavaScript optimiza este proceso enormemente. Incluso puede saltear la creación del objeto extra por completo. Pero aún se debe adherir a la especificación y comportarse como si creara uno.
7272

73-
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:
73+
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:
7474

7575
```js run
7676
let n =1.23456;
7777

7878
alert( n.toFixed(2) ); // 1.23
7979
```
8080

81-
We'll see more specific methods in chapters<info:number>and<info:string>.
81+
Veremos más métodos específicos en los capítulos<info:number>y<info:string>.
8282

8383

84-
````warn header="Constructors `String/Number/Boolean`are for internal use only"
85-
Some languages like Java allow us to explicitly create "wrapper objects" for primitives using a syntax like `new Number(1)`or`new Boolean(false)`.
84+
````warn header="Los constructores `String/Number/Boolean`son de uso interno solamente"
85+
Algunos lenguajes como Java permiten crear "wrapper objects" para primitivos explícitamente usando una sintaxis como `new Number(1)`o`new Boolean(false)`.
8686

87-
In JavaScript, that's also possible for historical reasons, but highly**unrecommended**. Things will go crazy in several places.
87+
En JavaScript, eso también es posible por razones históricas, pero firmemente**desaconsejado**. Las cosas enloquecerían en varios lugares.
8888

89-
For instance:
89+
Por ejemplo:
9090

9191
```js run
9292
alert( typeof0 ); // "number"
9393

9494
alert( typeofnewNumber(0) ); // "object"!
9595
```
9696

97-
Objects are always truthy in `if`, so here the alert will show up:
97+
Los objetos siempre son true en un `if`, entonces el alert mostrará:
9898

9999
```js run
100-
letzero=newNumber(0);
100+
letcero=newNumber(0);
101101

102-
if (zero){//zero is true, because it's an object
103-
alert( "zero is truthy!?!" );
102+
if (cero){//cero es true, porque es un objeto
103+
alert( "cero es verdadero?!?" );
104104
}
105105
```
106106

107-
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).
107+
Por otro lado, usar las mismas funciones`String/Number/Boolean`sin`new`es totalmente sano y útil. Ellas convierten un valor al tipo correspondiente: a un string, number, o boolean (primitivo).
108108

109-
For example, this is entirely valid:
109+
Por ejemplo, esto es perfectamente válido::
110110
```js
111-
let num =Number("123"); //convert a string to number
111+
let num =Number("123"); //convierte string a number
112112
```
113113
````
114114
115115
116-
````warn header="null/undefined have no methods"
117-
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".
116+
````warn header="null/undefined no poseen métodos"
117+
Los primitivos especiales `null` y `undefined` son excepciones. No tienen "wrapper objects" correspondientes y no proveen métodos. En ese sentido son "lo más primitivo".
118118
119-
An attempt to access a property of such value would give the error:
119+
El intento de acceder a una propiedad de tal valor daría error:
120120
121121
```js run
122122
alert(null.test); // error
123123
````
124124

125-
## Summary
125+
## Resumen
126126

127-
-Primitives except `null`and`undefined`provide many helpful methods. We will study those in the upcoming chapters.
128-
-Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.
127+
-Los primitivos excepto `null`y`undefined`proveen muchos métodos útiles. Los estudiaremos en los próximos capítulos.
128+
-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

Comments
(0)