Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Methods of primitives#151

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
otmon76 merged 2 commits intojavascript-tutorial:masterfromotmon76:1.5.1
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,24 @@

Try running it:
Zkuste si to spustit:

```js run
letstr = "Hello";
letřetězec = "Ahoj";

str.test = 5; // (*)
řetězec.test = 5; // (*)

alert(str.test);
alert(řetězec.test);
```

Depending on whether you have`use strict`or not, the result may be:
1. `undefined` (no strict mode)
2.An error (strict mode).
Podle toho, zda máte`use strict`nebo ne, výsledek může být:
1. `undefined` (nestriktní režim).
2.Chyba (striktní režim).

Why? Let's replay what's happening at line `(*)`:
Proč? Přehrajme si, co se děje na řádku `(*)`:

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.
1.Když přistoupíme k vlastnosti proměnné `řetězec`, vytvoří se „obal“.
2.Ve striktním režimu zápis do něj znamená chybu.
3.V nestriktním režimu bude operace s touto vlastností provedena, objekt získá vlastnost`test`, ale poté „obal“ zmizí, takže na posledním řádku nemá `řetězec` po této vlastnosti ani stopu.

**This example clearly shows that primitives are not objects.**
**Tento příklad jednoznačně dokazuje, že primitivy nejsou objekty.**

They can't store additional data.
Nelze do nich ukládat další data.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,17 +2,17 @@ importance: 5

---

#Can I add a string property?
#Mohu přidat vlastnost do řetězce?


Consider the following code:
Uvažujme následující kód:

```js
letstr = "Hello";
letřetězec = "Ahoj";

str.test = 5;
řetězec.test = 5;

alert(str.test);
alert(řetězec.test);
```

What do you think, will it work? What will be shown?
Co myslíte, bude to fungovat? Co se zobrazí?
116 changes: 58 additions & 58 deletions1-js/05-data-types/01-primitives-methods/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,129 +1,129 @@
#Methods of primitives
#Metody primitivů

JavaScriptallows 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).
JavaScriptnám umožňuje pracovat s primitivy (řetězci, čísly atd.), jako by to byly objekty. Poskytuje i metody, které na nich můžeme volat jako na objektech. V dalších kapitolách je prostudujeme, ale nejprve se podíváme, jak to funguje, protože primitivy samozřejmě nejsou objekty (a zde to ještě více ozřejmíme).

Let's look at the key distinctions between primitives and objects.
Podíváme se na klíčové rozdíly mezi primitivy a objekty.

A primitive
Primitiv:

-Is a value of a primitive type.
-There are 7 primitive types: `string`, `number`, `bigint`, `boolean`, `symbol`, `null`and `undefined`.
-Představuje hodnotu primitivního typu.
-Existuje 7 primitivních typů: `string`, `number`, `bigint`, `boolean`, `symbol`, `null`a `undefined`.

An object
Objekt:

-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 #"0170e611a7003c8066a6b628886ce8028bc9da00ff884f6362a51ac633bec303">-Dokáže obsahovat více hodnot uložených ve svých vlastnostech.
-Může být vytvořen pomocí `{}`,např. `{jméno: "Jan",věk: 30}`.V JavaScriptu jsou i jiné druhy objektů, například funkce jsou objekty.

One of the best things about objects is that we can store a function as one of its properties.
Jedna z nejlepších věcí na objektech je, že jako jejich vlastnost můžeme uložit funkci.

```js run
letjohn = {
name: "John",
sayHi: function() {
alert("Hi buddy!");
letjan = {
jméno: "Jan",
řekniAhoj: function() {
alert("Ahoj kámo!");
}
};

john.sayHi(); //Hi buddy!
jan.řekniAhoj(); //Ahoj kámo!
```

So here we've made an object `john` with the method `sayHi`.
Zde jsme tedy vytvořili objekt `jan` s metodou `řekniAhoj`.

Many built-in objects already exist, such as those that work with dates, errors, HTMLelements, etc. They have different properties and methods.
JavaScript obsahuje mnoho vestavěných objektů, například ty, které pracují s daty, chybami, HTMLprvky a podobně. Mají různé vlastnosti a metody.

But, these features come with a cost!
Tyto vlastnosti však mají svou cenu!

Objects are "heavier" than primitives. They require additional resources to support the internal machinery.
Objekty jsou „těžší“ než primitivy. Vyžadují více zdrojů, které zatěžují vnitřní stroj.

##A primitive as an object
##Primitiv jako objekt

Here's the paradox faced by the creator of JavaScript:
Tvůrci JavaScriptu čelili následujícímu paradoxu:

-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 using methods.
-Primitives must be as fast and lightweight as possible.
-Existuje mnoho věcí, které člověk chce dělat s primitivy, jakými jsou řetězec nebo číslo. Bylo by skvělé přistupovat k nim pomocí metod.
-Primitivy musejí být co nejrychlejší a co nejmenší.

The solution looks a little bit awkward, but here it is:
Řešení vypadá trochu těžkopádně, ale je zde:

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 thattowork, a special "object wrapper" that provides the extra functionality is created, and then is destroyed.
1.Primitiv je pořád primitiv. Jednoduchá hodnota, po jaké toužíme.
2.Jazyk umožňuje přístup k metodám a vlastnostem řetězců, čísel, booleanů a symbolů.
3.Abytofungovalo, vytvoří se speciální objekt zvaný „obal“ neboli „wrapper“, který tuto přídavnou funkcionalitu poskytne a pak bude zničen.

The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean`, `Symbol`and `BigInt`.Thus, they provide different sets of methods.
Tyto „objektové obaly“ jsou pro každý primitivní typ jiné a nazývají se: `String`, `Number`, `Boolean`, `Symbol`a `BigInt`.Poskytují tedy různé sady metod.

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`.
Například existuje řetězcová metoda [řetězec.toUpperCase()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase), která vrací `řetězec` zapsaný velkými písmeny.

Here's how it works:
Funguje následovně:

```js run
letstr = "Hello";
letřetězec = "Ahoj";

alert(str.toUpperCase() ); //HELLO
alert(řetězec.toUpperCase() ); //AHOJ
```

Simple, right? Here's what actually happens in `str.toUpperCase()`:
Jednoduché, že? Ve skutečnosti se v `řetězec.toUpperCase()` děje následující:

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.Řetězec `řetězec` je primitiv. V okamžiku přístupu k jeho vlastnosti se tedy vytvoří speciální objekt, který zná hodnotu tohoto řetězce a obsahuje užitečné metody, např. `toUpperCase()`.
2.Tato metoda se spustí a vrátí nový řetězec (který je zobrazen funkcí `alert`).
3.Speciální objekt se zničí a zůstane samotný primitiv `řetězec`.

So primitives can provide methods, but they still remain lightweight.
Primitivy tedy mohou poskytovat metody, ale samy zůstávají malé.

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.
JavaScriptový motor tento proces značně optimalizuje. Může dokonce úplně vynechat vytvoření nového objektu. Stále však musí dodržovat specifikaci a chovat se tak, jako by jej vytvořil.

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:
I čísla mají své vlastní metody, například[toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)zaokrouhluje číslo se zadanou přesností:

```js run
let n = 1.23456;

alert( n.toFixed(2) ); // 1.23
```

We'll see more specific methods in chapters<info:number>and <info:string>.
Další specifické metody uvidíme v kapitolách<info:number>a <info:string>.


````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)`.
````warn header="Konstruktory `String/Number/Boolean`jsou jen pro interní použití"
Některé jazyky, např. Java, nám umožňují explicitně vytvářet „obaly“ pro primitivy pomocí syntaxe typu`new Number(1)`nebo `new Boolean(false)`.

In JavaScript, that's also possible for historical reasons, but highly **unrecommended**.Things will go crazy in several places.
V JavaScriptu je to z historických důvodů také možné, ale důrazně **nedoporučované**.Skript se začne chovat bláznivě hned na několika místech.

For instance:
Například:

```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:
Objekty jsou v`if` vždy pravdivé, takže zde se zobrazí hlášení:

```js run
letzero = new Number(0);
letnula = new Number(0);

if (zero) { //zero is true, because it's an object
alert( "zero is truthy!?!" );
if (nula) { //nula je pravdivá, protože je to objekt
alert( "nula je pravdivá!?!" );
}
```

On the other hand, using the same functions`String/Number/Boolean`without `new`is totally fine and useful thing. They convert a value to the corresponding type: to a string, a number, or a boolean (primitive).
Naproti tomu použití stejné funkce`String/Number/Boolean`bez `new`je zcela správná a užitečná věc. Funkce převede hodnotu na odpovídající typ: na řetězec, na číslo nebo na boolean (na primitiv).

For example, this is entirely valid:
Například tohle je zcela v pořádku:

```js
letnum = Number("123"); //convert a string to number
letčíslo = Number("123"); //převede řetězec na číslo
```
````


````warn header="null/undefinedhave 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/undefinednemají žádné metody"
Speciální primitivy`null`a `undefined`představují výjimky. Nemají odpovídající „obaly“ a neposkytují žádné metody. V určitém smyslu slova jsou vlastně „ty nejprimitivnější“.

An attempt to access a property of such value would give the error:
Pokus o přístup k vlastnosti takové hodnoty ohlásí chybu:

```js run
alert(null.test); //error
alert(null.test); //chyba
````

##Summary
##Shrnutí

-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.
-Primitivy s výjimkou`null`a `undefined`poskytují mnoho užitečných metod. Prostudujeme je v následujících kapitolách.
-Formálně tyto metody pracují na dočasných objektech, ale JavaScriptové motory jsou dobře vyladěny, aby je vnitřně optimalizovaly, takže jejich volání není nákladné.

[8]ページ先頭

©2009-2025 Movatter.jp