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 ens permet treballar amb primitius (cadena de caràcters, nombres, etc.) com si fóssen objectes.
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
+
També aporta mètodes propiament anomenats. Els estudiarem aviat, però primer veure'm com funciona perquè, per descomptat, els primitius no són objectes (i ho deixarem encara més clar).
6
6
7
-
Let's look at the key distinctions between primitives and objects.
7
+
Fixem-nos en les distincions claus entre primitius i objectes.
8
8
9
-
A primitive
9
+
Un primitiu
10
10
11
-
-Is a value of a primitive type.
12
-
-There are 6 primitive types: `string`, `number`, `boolean`, `symbol`, `null`and`undefined`.
11
+
-Es un valor d'un tipus primitiu.
12
+
-Hi ha 6 tipus primitius: `string`, `number`, `boolean`, `symbol`, `null`i`undefined`.
13
13
14
-
An object
14
+
Un objecte
15
15
16
-
-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 capaç d'emmagatzemar múltiples tipus com a propietats.
17
+
-Es poden crear amb`{}`, com ara: `{name: "John", age: 30}`. Hi ha altres tipus d'objectes en Javascript: les funcions, per exemple, són objectes.
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 les millors coses dels objectes és que podem emmagatzemar una funció com a propietats.
20
20
21
21
```js run
22
22
let john = {
@@ -29,74 +29,75 @@ 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
+
Ací hem creat un objecte `john`amb el mètode`sayHi`.
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
+
Hi ha objectes integrats de sèrie, com els que que treballen amb dates, errors, elements HTML, etc. Tenen diferents propietats i mètodes.
35
35
36
-
But, these features come with a cost!
36
+
Però, aquestes funcionalitats tenen un cost!
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
+
Els objectes són més "pesats" que els primitius. Requereixen recursos addicionals per a suportar aquesta maquinària interna. Però com que les propietats i els mètodes són molt útils en programació, el motor de Javascript tracta d'optimitzar-los per a reduir-ne la càrrega.
39
39
40
-
## A primitive as an object
41
40
42
-
Here's the paradox faced by the creator of JavaScript:
43
41
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.
42
+
## Primitius com a objectes
46
43
47
-
The solution looks a little bit awkward, but here it is:
44
+
Heus ací la paradoxa a la qual va fer front el creador de Javascript:
48
45
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. In order for that to work, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
46
+
- Hi ha moltes coses que hom voldria fer amb una primitiu (com una cadena de caràcters o un nombre). Seria genial accedir-hi a través de mètodes.
47
+
- Els primitius han de ser tan ràpids i lleugers com siga possible.
52
48
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.
49
+
La solució sembla una mica estranya, però:
54
50
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.
51
+
- Els primitius són encara primitius. Un valor únic, com voliem.
52
+
- El llenguatge permet accedir mètodes i propietats de cadenes de caràcters, nombres, booleans i símbols.
53
+
- Per a que això funcione, es crea un "objecte embolcall" que aporta funcionalitats extra, i després es destrueix.
56
54
57
-
Here's how it works:
55
+
Els "objectes embolcall" són diferents per a cada tipus primitiu i s'anomenen: `String`, `Number`, `Boolean` i `Symbol`. Així, aporten diferents mètodes.
56
+
57
+
Per exemple, existeix un mètode [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) que retorna una cadena de caràcters en majúscula.
58
+
59
+
Heus ací com funciona:
58
60
59
61
```js run
60
62
let str ="Hello";
61
63
62
64
alert( str.toUpperCase() ); // HELLO
63
65
```
64
66
65
-
Simple, right? Here's what actually happens in`str.toUpperCase()`:
67
+
Simple, veritat? El que realment ocorre en`str.toUpperCase()`és:
66
68
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.
69
+
1.La cadena de caràcters `str`és un primitiu. En el moment d'accedir la propietat, un objecte especial es crea, el qual coneix el valor de la cadena i conté mètodes útils, com`toUpperCase()`.
70
+
2.El mètode retorna una cadena de caràcters nova (que es mostra amb`alert`).
71
+
3.L'objecte especial es destrueix, deixant només el primitiu `str`.
70
72
71
-
So primitives can provide methods, but they still remain lightweight.
73
+
Per tant, els primitius poden tenir mètodes, però mantenir-se lleugers al mateix temps.
72
74
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.
75
+
El motor de Javascript optimitza en gran mesura el procés. Fins i tot pot saltar-se la creació de l'objecte addicional. Però s'adhereix al es especificacions i es comporta com si en crees un.
74
76
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:
77
+
Un nombre té mètodes propis, per exemple, [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)arrodoneix el número amb la precisió indicada:
76
78
77
79
```js run
78
80
let n =1.23456;
79
81
80
82
alert( n.toFixed(2) ); // 1.23
81
83
```
82
84
83
-
We'll see more specific methods in chapters <info:number> and <info:string>.
84
-
85
+
Veurem mètodes més específics als capítols <info:number> and <info:string>.
85
86
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)`.
87
+
````warn header="Els constructors String/Number/Boolean`són només per a ús intern"
88
+
Algunes llenguatges com Java ens permeten crear "objectes embolcall" per a primitius explicitament amb sintaxi de l'estil`new Number(1)`o`new Boolean(false)`.
88
89
89
-
In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places.
90
+
En Javascript, això també és possible per raons històriques, però **no és recomanable**. Les coses poden tornar-se imprevisibles.
90
91
91
-
For instance:
92
+
Per exemple:
92
93
93
94
```js run
94
95
alert( typeof0 ); // "number"
95
96
96
97
alert( typeofnewNumber(0) ); // "object"!
97
98
```
98
99
99
-
Objects are always truthy in `if`, so here the alert will show up:
100
+
Els objectes són sempre s'avaluen com a vertaders en `if`, de manera que l'alerta serà:
100
101
101
102
```js run
102
103
let zero =newNumber(0);
@@ -106,25 +107,25 @@ if (zero) { // zero is true, because it's an object
106
107
}
107
108
```
108
109
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).
110
+
Alternativament, emprar les mateixes funcions `String/Number/Boolean` sense `new` és totalment útil i assenyat. Converteixen el valor primitiu corresponent: cadena de caràcters, nombre o booleà.
111
+
112
+
Per exemple, això és perfectament vàlid:
110
113
111
-
For example, this is entirely valid:
112
114
```js
113
-
let num =Number("123"); //convert a string to number
115
+
let num =Number("123"); //converteix 'string' a 'number'
114
116
```
115
117
````
116
118
119
+
````warn header="null/undefined no tenen mètodes"
120
+
Els primitius especials `null` i `undefined` són excepcions. No tenen "objectes embolcall" corresponents i tampoc mètodes. D'alguna forma, són els tipus "més primitius",
117
121
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".
120
-
121
-
An attempt to access a property of such value would give the error:
122
+
L'intent d'accedir a una propietat d'aquest tipus resultaria en error:
122
123
123
-
```js run
124
+
```js run
124
125
alert(null.test); // error
125
126
````
126
127
127
-
## Summary
128
+
## Resum
128
129
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.
130
+
-Els primitius, a excepció de `null`i `undefined`tenen mètodes molt útils. Els estudiarem en els capítols següents.
131
+
-En un sentit estricte, aquests mètodes funcionen a través d'objectes temporals, però els motors de Javascript estan ben preparats per a optimizar-los, de manera que no perjudiquen el rendiment.
0 commit comments