Skip to content

Commit c52b19c

Browse files
authored
Merge pull request #30 from andesol/master
Article translation
2 parents a05ea8c + cd2f7c7 commit c52b19c

File tree

3 files changed

+69
-66
lines changed

3 files changed

+69
-66
lines changed
Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
Try running it:
2+
Intenta executar:
33

44
```js run
55
let str = "Hello";
@@ -9,18 +9,19 @@ 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+
Depenent de si tens `use strict` o no, el resultat pot ser:
1513

16-
Why? Let's replay what's happening at line `(*)`:
14+
1. `undefined` (mode no estricte)
15+
2. un error (mode estricte)
1716

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.
17+
Per què? Parem esment al que passa a la línia `(*)`:
2118

22-
So, without strict mode, in the last line `str` has no trace of the property.
19+
1. Quan s'accedeix a una propietat de `str`, es crea un "objecte embolcall".
20+
2. En mode estricte, escriure-hi és una error.
21+
3. Alternativament, l'operació amb la propietat continua, l'objecte agafa la propietat `test`, però després d'això "l'objecte embolcall" desapareix.
2322

24-
**This example clearly shows that primitives are not objects.**
23+
Així, sense el mode estricte, en l'última línia no queda ni rastre de la propietat de `str`.
2524

26-
They can't store additional data.
25+
**Aquest exemple mostra clarament que els primitius no són objectes.**
26+
27+
No poden emmagatzemar informació adicional.
Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
importance: 5
1+
importància: 5
22

33
---
44

5-
# Can I add a string property?
5+
# Puc afegir una propietat a una cadena de caràcters?
66

77

8-
Consider the following code:
8+
Considera el codi següent:
99

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

18-
How do you think, will it work? What will be shown?
18+
Com creus que funcionarà? Què creus que es mostrarà?
19+
Lines changed: 52 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
# Methods of primitives
1+
# Mètodes dels primitius
22

3-
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.
44

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).
66

7-
Let's look at the key distinctions between primitives and objects.
7+
Fixem-nos en les distincions claus entre primitius i objectes.
88

9-
A primitive
9+
Un primitiu
1010

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`.
1313

14-
An object
14+
Un objecte
1515

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.
1818

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.
2020

2121
```js run
2222
let john = {
@@ -29,74 +29,75 @@ let john = {
2929
john.sayHi(); // Hi buddy!
3030
```
3131

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`.
3333

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.
3535

36-
But, these features come with a cost!
36+
Però, aquestes funcionalitats tenen un cost!
3737

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.
3939

40-
## A primitive as an object
4140

42-
Here's the paradox faced by the creator of JavaScript:
4341

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
4643

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:
4845

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.
5248

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ò:
5450

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.
5654

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:
5860

5961
```js run
6062
let str = "Hello";
6163

6264
alert( str.toUpperCase() ); // HELLO
6365
```
6466

65-
Simple, right? Here's what actually happens in `str.toUpperCase()`:
67+
Simple, veritat? El que realment ocorre en `str.toUpperCase()`és:
6668

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`.
7072

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.
7274

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.
7476

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:
7678

7779
```js run
7880
let n = 1.23456;
7981

8082
alert( n.toFixed(2) ); // 1.23
8183
```
8284

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>.
8586

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)`.
8889

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.
9091

91-
For instance:
92+
Per exemple:
9293

9394
```js run
9495
alert( typeof 0 ); // "number"
9596

9697
alert( typeof new Number(0) ); // "object"!
9798
```
9899

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à:
100101

101102
```js run
102103
let zero = new Number(0);
@@ -106,25 +107,25 @@ if (zero) { // zero is true, because it's an object
106107
}
107108
```
108109

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:
110113

111-
For example, this is entirely valid:
112114
```js
113-
let num = Number("123"); // convert a string to number
115+
let num = Number("123"); // converteix 'string' a 'number'
114116
```
115117
````
116118
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",
117121
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:
122123
123-
```js run
124+
```js run
124125
alert(null.test); // error
125126
````
126127

127-
## Summary
128+
## Resum
128129

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

Comments
 (0)