pFad - Phone/Frame/Anonymizer/Declutterfier! Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

URL: http://github.com/javascript-tutorial/uk.javascript.info/pull/10.diff

ся. -The "object wrappers" are different for each primitive type and are called: `String`, `Number`, `Boolean` and `Symbol`. Thus, they provide different sets of methods. +Для кожного примітиву створюється своя "обгортка": `String`, `Number`, `Boolean` та `Symbol`. Отже, вони містять різні набори методів. -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. +Наприклад: існує метод [str.toUpperCase()](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase) якій повертає рядок з великими літерами. -Here's how it works: +Ось як він працює: ```js run -let str = "Hello"; +let str = "Привіт"; -alert( str.toUpperCase() ); // HELLO +alert( str.toUpperCase() ); // ПРИВІТ ``` -Simple, right? Here's what actually happens in `str.toUpperCase()`: +Не складно, так? Ось що саме трапляється в `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. Рядок `str` є примітивом. Тому під час звернення до його властивості створюється спеціальний об'єкт, який знає значення рядка і має корисні методи, такі як `toUpperCase()`. +2. Цей метод виконується і повертає новий рядок (що показує `alert`). +3. Спеціальний об'єкт руйнується, залишаючи лише примітив `str`. -So primitives can provide methods, but they still remain lightweight. +Отже примітиви можуть надавати методи, але залишаються "легкими". -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. +Двигун JavaScript добре оптимізує цей процес. Він навіть може пропустити створення додаткового об'єкта взагалі. Але він все ще повинен дотримуватися специфікації і вести себе так, наче він її створює. -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: +Число має свої методи, наприклад: [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) - округлює число до заданої точності: ```js run let n = 1.23456; @@ -80,15 +80,15 @@ let n = 1.23456; alert( n.toFixed(2) ); // 1.23 ``` -We'll see more specific methods in chapters and . +Ми переглянемо більш конкретні методи у розділах та . -````warn header="Constructors `String/Number/Boolean` are for internal use only" -Some languages like Java allow us to create "wrapper objects" for primitives explicitly using a syntax like `new Number(1)` or `new Boolean(false)`. +````warn header="Конструктори `String/Number/Boolean` лише для внутрішнього використання" +Деякі мови як Java дозволяють створювати "об'єкт обгортку" для примітивів явно використовуючи синтаксис як `new Number(1)` або `new Boolean(false)`. -In JavaScript, that's also possible for historical reasons, but highly **unrecommended**. Things will go crazy in several places. +У JavaScript це також можливо з історичних причин, але надзвичайно **не рекомендується**. Це призведе до непередбачуваних речей. -For instance: +Наприклад: ```js run alert( typeof 1 ); // "number" @@ -96,35 +96,36 @@ alert( typeof 1 ); // "number" alert( typeof new Number(1) ); // "object"! ``` -And because what follows, `zero`, is an object, the alert will show up: +та завдяки тому що `zero` об'єкт, ми побачимо алерт: ```js run let zero = new Number(0); -if (zero) { // zero is true, because it's an object - alert( "zero is truthy?!?" ); +if (zero) { // zero є true, тому що це об'єкт + alert( "zero є true?!?" ); } ``` -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). -For example, this is entirely valid: +З іншого боку, використання тих же самих функцій `String / Number / Boolean` без `new` є абсолютно розумною і корисною річчю. Вони перетворюють значення у відповідний тип: до рядка, числа або булевого (примітиву). + +Наприклад, це цілком правильно: ```js -let num = Number("123"); // convert a string to number +let num = Number("123"); // конвертує рядок в число ``` ```` -````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 не мають методів" +Винятки становлять спеціальні примітиви `null` і `undefined`. Вони не мають відповідних "об'єктів обгорток" і не надають ніяких методів. Ми можемо назвати їх "найпримітивнішими". -An attempt to access a property of such value would give the error: +Спроба доступу до властивості такого значення дасть помилку: ```js run -alert(null.test); // error +alert(null.test); // помилка ```` -## Summary +## Підсумки -- 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. +- Примітиви, крім `null` і `undefined`, дають багато корисних методів. Ми вивчимо їх у наступних розділах. +- Формально, ці методи працюють через тимчасові об'єкти, але двигун JavaScript оптимізовано для швидкого виконання цих операцій, тому нам не треба хвилюватися. pFad - Phonifier reborn

Pfad - The Proxy pFad © 2024 Your Company Name. All rights reserved.





Check this box to remove all script contents from the fetched content.



Check this box to remove all images from the fetched content.


Check this box to remove all CSS styles from the fetched content.


Check this box to keep images inefficiently compressed and original size.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy