Skip to content

Methods of primitives #62

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/05-types/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ W JavaScripcie nie ma takiego typu. Mamy do dyspozycji jedynie `string`. Ciąg z

Typ logiczny (ang. *boolean*) posiada dwie wartości: `true` (prawda) lub `false` (fałsz).

Ty logiczny jest najczęsciej używany do przechowywania wartości pokroju "tak/nie", gdzie `true` to "tak, prawda", a `false` oznacza "nie, nieprawda".
Typ logiczny jest najczęściej używany do przechowywania wartości pokroju "tak/nie", gdzie `true` to "tak, prawda", a `false` oznacza "nie, nieprawda".

Na przykład:

Expand Down
2 changes: 1 addition & 1 deletion 1-js/02-first-steps/06-type-conversions/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Rzutowanie do typu liczbowego następuje automatycznie w wyniku matematycznych w
Na przykład przy dzieleniu (`/`) z udziałem wartości nie będących liczbami:

```js run
alert( "6" / "2" ); // 3, wartości tekstowe są zamienane na liczby
alert( "6" / "2" ); // 3, wartości tekstowe są zamieniane na liczby
```

Możemy użyć funkcji `Number(value)`, aby jawnie rzutować zmienną `value` na liczbę.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@

Try running it:
Spróbuj to uruchomić:

```js run
let str = "Hello";
let str = "Witaj";

str.test = 5; // (*)

alert(str.test);
```

Depending on whether you have `use strict` or not, the result may be:
1. `undefined` (no strict mode)
2. An error (strict mode).
W zależności czy używasz `use strict` czy też nie, wynik może być różny:

Why? Let's replay what's happening at line `(*)`:
1. `undefined` (brak trybu nowoczesnego)
2. Błąd (tryb nowoczesny).

1. When a property of `str` is accessed, a "wrapper object" is created.
2. In strict mode, writing into it is an error.
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.
Dlaczego? Spróbujmy odtworzyć co dzieje się w lini `(*)`:

**This example clearly shows that primitives are not objects.**
1. Kiedy uzyskujemy dostęp do własności `str`, tworzony jest "wrapper obiektu".
2. W trybie nowoczesnym przypisywanie wartości do niego powoduje błąd.
3. W przeciwnym wypadku operacja przypisania wartości jest kontynuowana, obiekt dostaje własność `test`, ale zaraz po tym "wrapper obiektu" znika i w w ostatnim wierszu `str` nie może dostać się do własności obiektu.

They can't store additional data.
**Ten przykład jasno pokazuje że typy podstawowe nie są obiektami.**

Nie mogą przechowywać dodatkowych informacji.
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@ importance: 5

---

# Can I add a string property?
# Czy mogę dodać właściwość string?


Consider the following code:
Rozważ następujący kod:

```js
let str = "Hello";
let str = "Witaj";

str.test = 5;

alert(str.test);
```

How do you think, will it work? What will be shown?
Jak sądzisz, czy to zadziała? Co się pokaże?
160 changes: 77 additions & 83 deletions 1-js/05-data-types/01-primitives-methods/article.md
Original file line number Diff line number Diff line change
@@ -1,128 +1,122 @@
# Methods of primitives

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

Let's look at the key distinctions between primitives and objects.

A primitive

- Is a value of a primitive type.
- There are 7 primitive types: `string`, `number`, `bigint`, `boolean`, `symbol`, `null` and `undefined`.

An object

- Is capable of storing multiple values as properties.
- Can be created with `{}`, for instance: `{name: "John", age: 30}`. There are other kinds of objects in JavaScript: functions, for example, are objects.

One of the best things about objects is that we can store a function as one of its properties.

# Metody typów podstawowych
JavaScript pozwala na pracę z typami podstawowymi (ciągi znaków, liczby, itd.) w taki sam sposób jakby były obiektami. Dostarczają one także metod, które można wywołać tak samo jak w przypadku obiektów. Wkrótce przestudiujemy te metody, ale najpierw sprawdźmy jak wartości podstawowe działają, ponieważ oczywiście typy podstawowe nie są obiektami (za chwilę szerzej to wyjaśnimy).
Spójrzmy na kluczowe różnice pomiędzy typami podstawowymi, a obiektami.
Typ podstawowy
- Jest wartością typu podstawowego.
- Wyróżniamy 7 typów podstawowych: `tekstowy`, `liczbowy`, `bigint`, `logiczny`, `symbol`, `null` and `undefined`.
Obiekt
- Jest w stanie przechowywać wiele wartości jako własności.
- Można go stworzyć za pomocą`{}`, na przykład: `{name: "Janek", age: 30}`. Są także inne rodzaje obiektów w JavaScript: na przykład funkcje są obiektami.
Jedną z najlepszych rzeczy w obiektach jest to, że możemy przechowywać funkcje jako własność obiektu.
```js run
let john = {
name: "John",
let janek = {
name: "Jan",
sayHi: function() {
alert("Hi buddy!");
alert("Cześć kolego!");
}
};

john.sayHi(); // Hi buddy!
jan.sayHi(); // Cześć kolego!
```

So here we've made an object `john` with the method `sayHi`.

Many built-in objects already exist, such as those that work with dates, errors, HTML elements, etc. They have different properties and methods.

But, these features come with a cost!

Objects are "heavier" than primitives. They require additional resources to support the internal machinery.

## A primitive as an object

Here's the paradox faced by the creator of JavaScript:

- 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.
- Primitives must be as fast and lightweight as possible.

The solution looks a little bit awkward, but here it is:

1. Primitives are still primitive. A single value, as desired.
2. The language allows access to methods and properties of strings, numbers, booleans and symbols.
3. In order for that to work, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.

The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods.

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

Here's how it works:


Stworzyliśmy tutaj obiekt `janek` z metodą `sayHi`

Wiele wbudowanych obiektów już istnieje, na przykład takie jak te, które pracują z datami, błędami, elementami HTML, itd. Mają one różne własności i metody.

Pamiętaj jednak, że te funkcje mają swój koszt!

Obiekty są "cięższe" niż typy podstawowe. Wymagają dodatkowych zasobów żeby do obsługi wewnętrznych maszyn.

## Typ podstawowy jest jak obiekt


Oto paradoks, za którym którym stoi twórca JavaScript:

- Jest wiele rzeczy, które chciałoby się zrobić z typami podstawowymi, takimi jak tekstowy lub liczba. Byłoby wspaniale uzyskać dostęp do nich jako metod.
- Typy podstawowe są szybkie i muszą ważyć najmniej jak to możliwe.

Rozwiązanie wygląda jest trochę dziwne. Oto ono:

1. Typy podstawowe są wciąż typami podstawowymi. Pojedynczymi wartościami, tak jak zaprojektowano.
2. Język pozwala dostać się do metod i własności typu tekstowego, liczbowego, logicznego i symboli.
3. W tym celu stworzony został specjalny "wrapper obiektu", który dostarcza dodatkowych funkcji, a następnie jest on usuwany.

"Wrappery obiektów" są różne dla każdego typu podstawowego i nazywają się: `String`, `Number`, `Boolean` i `Symbol`. W ten sposób zapewniają różne zestawy metod.

Istnieje na przykład metoda typu tekstowego [str.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) która zwraca skapitalizowane `str`.
Oto jak działa:
```js run
let str = "Hello";
let str = "Cześć";

alert( str.toUpperCase() ); // HELLO
alert( str.toUpperCase() ); // CZEŚĆ
```
Proste, prawda ? Oto co dokładnie się dzieje wywołując `str.toUpperCase()`:

Simple, right? Here's what actually happens in `str.toUpperCase()`:

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()`.
2. That method runs and returns a new string (shown by `alert`).
3. The special object is destroyed, leaving the primitive `str` alone.
1. Ciąg znaków `str` jest typem podstawowym. W momencie gdy chcemy dostać się do jego własności, zostaje stworzony specjalny obiekt, który zna przypisaną do niego wartość i dostarcza przydatnych metod takich jak `toUpperCase()`.
2. Metoda zostaje uruchomiona i zwraca nowy ciąg znaków (pokazany za pomocą `alert`).
3. Nowo stworzony specjalny obiekt zostaje usunięty, pozostawiając sam typ podstawowy `str`.

So primitives can provide methods, but they still remain lightweight.
Tak więc typy podstawowe mogą dostarczać metod, ale wciąż pozostają lekkie.

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.
Silnik JavaScript silnie optymalizuje ten proces. Może nawet całkowicie pominąć tworzenie dodatkowego obiektu, ale wciąż ciąg znaków musi zachowywać się zgodne ze specyfikacją, tak jak gdyby został stworzony.

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:
Typ liczbowy ma swoje własne metody, na przykład, [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) zaokrągla liczb do podanej precyzji:

```js run
let n = 1.23456;

alert( n.toFixed(2) ); // 1.23
```
Więcej specyficznych metod poznamy w rozdziałach <info:number> i <info:string>.

We'll see more specific methods in chapters <info:number> and <info:string>.

````warn header="Konstruktory `String/Number/Boolean` są tylko do wewnętrznego odczytu"
Niektóre języki programowania takie jak Java pozwalają nam na stworzenie "wrapperów obiektów" dla typów podstawowych używając następującej składni: `new Number(1)` albo `new Boolean(false)`.

````warn header="Constructors `String/Number/Boolean` are for internal use only"
Some languages like Java allow us to explicitly create "wrapper objects" for primitives using a syntax like `new Number(1)` or `new Boolean(false)`.
W JavaScript także jest to możliwe z powodów historycznych, ale mocno **niezalecane**. W niektórych przypadkach powoduje to mocne niedopowiedzenia.

In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places.

For instance:
Na przykład:

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

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

Objects are always truthy in `if`, so here the alert will show up:

Obiekty są zawsze prawdziwe (ang. *truthy*) w `if`, więc ostrzeżenie zostanie wyświetlone:
```js run
let zero = new Number(0);

if (zero) { // zero is true, because it's an object
alert( "zero is truthy!?!" );
if (zero) { // zero jest prawdziwe, ponieważ jest obiektem
alert( "zero jest prawdziwe!?!" );
}
```

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).
Z drugiej strony, używając samych funkcji `String/Number/Boolean` bez operatora `new` jest całkowicie rozsądne i użyteczne. Zamieniają one wartości na odpowiadające im typy: typ tekstowy, liczbowy logiczny (typy podstawowe).

For example, this is entirely valid:
Na przykład jest to całkowicie poprawne:
```js
let num = Number("123"); // convert a string to number
let num = Number("123"); // zamienia ciąg znaków na liczbę
```
````


````warn header="null/undefined have no methods"
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".
````warn header="null/undefined nie mają metod."
Specjalne typy podstawowe `null` i `undefined` są wyjątkami. Nie mają odpowiadających im "wrapperów obiektów" i nie dostarczają metod. W pewnym sensie są najbardziej "podstawowe".

An attempt to access a property of such value would give the error:
Próba uzyskania dostępu do właściwości o takiej wartości spowodowałaby błąd:

```js run
alert(null.test); // error
alert(null.test); // błąd
````

## Summary
## Podsumowanie

- Primitives except `null` and `undefined` provide many helpful methods. We will study those in the upcoming chapters.
- Formally, these methods work via temporary objects, but JavaScript engines are well tuned to optimize that internally, so they are not expensive to call.
- Typy podstawowe oprócz `null` i `undefined` dostarczają wielu przydatnych metod. Przestudiujemy te metody w następnych rozdziałach.
- Formalnie metody te działają za pośrednictwem obiektów tymczasowych, ale silniki JavaScript są dobrze dostosowane i optymalizują to wewnętrznie, więc wywołanie ich nie jest drogie.