From 4b1a9203c547c019fc5398082ae19a3f3d4c3efe Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:15 -0500 Subject: initial commit --- files/bg/web/javascript/guide/index.html | 122 +++++ .../javascript/guide/text_formatting/index.html | 255 +++++++++ files/bg/web/javascript/index.html | 127 +++++ .../inheritance_and_the_prototype_chain/index.html | 563 +++++++++++++++++++ .../reference/classes/constructor/index.html | 130 +++++ .../reference/classes/extends/index.html | 112 ++++ .../bg/web/javascript/reference/classes/index.html | 431 +++++++++++++++ .../javascript/reference/classes/static/index.html | 135 +++++ .../bg/web/javascript/reference/errors/index.html | 31 ++ .../reference/errors/unexpected_type/index.html | 70 +++ .../reference/functions/arrow_functions/index.html | 394 ++++++++++++++ .../web/javascript/reference/functions/index.html | 596 +++++++++++++++++++++ .../reference/global_objects/array/index.html | 460 ++++++++++++++++ .../global_objects/array/splice/index.html | 155 ++++++ .../global_objects/arraybuffer/index.html | 96 ++++ .../javascript/reference/global_objects/index.html | 182 +++++++ .../reference/global_objects/promise/index.html | 253 +++++++++ files/bg/web/javascript/reference/index.html | 51 ++ .../operators/arithmetic_operators/index.html | 293 ++++++++++ .../web/javascript/reference/operators/index.html | 310 +++++++++++ .../index.html" | 248 +++++++++ 21 files changed, 5014 insertions(+) create mode 100644 files/bg/web/javascript/guide/index.html create mode 100644 files/bg/web/javascript/guide/text_formatting/index.html create mode 100644 files/bg/web/javascript/index.html create mode 100644 files/bg/web/javascript/inheritance_and_the_prototype_chain/index.html create mode 100644 files/bg/web/javascript/reference/classes/constructor/index.html create mode 100644 files/bg/web/javascript/reference/classes/extends/index.html create mode 100644 files/bg/web/javascript/reference/classes/index.html create mode 100644 files/bg/web/javascript/reference/classes/static/index.html create mode 100644 files/bg/web/javascript/reference/errors/index.html create mode 100644 files/bg/web/javascript/reference/errors/unexpected_type/index.html create mode 100644 files/bg/web/javascript/reference/functions/arrow_functions/index.html create mode 100644 files/bg/web/javascript/reference/functions/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/array/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/index.html create mode 100644 files/bg/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/bg/web/javascript/reference/index.html create mode 100644 files/bg/web/javascript/reference/operators/arithmetic_operators/index.html create mode 100644 files/bg/web/javascript/reference/operators/index.html create mode 100644 "files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" (limited to 'files/bg/web/javascript') diff --git a/files/bg/web/javascript/guide/index.html b/files/bg/web/javascript/guide/index.html new file mode 100644 index 0000000000..efc0745c96 --- /dev/null +++ b/files/bg/web/javascript/guide/index.html @@ -0,0 +1,122 @@ +--- +title: Ръководство по JavaScript +slug: Web/JavaScript/Guide +tags: + - JavaScript + - ръководство +translation_of: Web/JavaScript/Guide +--- +
{{jsSidebar("JavaScript Guide")}}
+ +

Ръководството по JavaScript ви обяснява как да използвате JavaScript и ви дава обща представа за езика. Ако се нуждаете от изчерпателни сведения за отделна възможност на езика, потърсете в Справочника за JavaScript.

+ +

Глави

+ +

This Guide is divided into several chapters:

+ + + + + + + + + +

{{Next("Web/JavaScript/Guide/Introduction")}}

diff --git a/files/bg/web/javascript/guide/text_formatting/index.html b/files/bg/web/javascript/guide/text_formatting/index.html new file mode 100644 index 0000000000..b96734f66e --- /dev/null +++ b/files/bg/web/javascript/guide/text_formatting/index.html @@ -0,0 +1,255 @@ +--- +title: Text formatting +slug: Web/JavaScript/Guide/Text_formatting +translation_of: Web/JavaScript/Guide/Text_formatting +--- +
{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}
+ +

This chapter introduces how to work with strings and text in JavaScript.

+ +

Strings

+ +

JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values  (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects.

+ + + +

String literals

+ +

You can create simple strings using either single or double quotes:

+ +
'foo'
+"bar"
+ +

More advanced strings can be created using escape sequences:

+ +

Hexadecimal escape sequences

+ +

The number after \x is interpreted as a hexadecimal number.

+ +
'\xA9' // "©"
+
+ +

Unicode escape sequences

+ +

The Unicode escape sequences require at least four hexadecimal digits following \u.

+ +
'\u00A9' // "©"
+ +

Unicode code point escapes

+ +

New in ECMAScript 2015. With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to 0x10FFFF. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.

+ +

See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.

+ +
'\u{2F804}'
+
+// the same with simple Unicode escapes
+'\uD87E\uDC04'
+ +

String objects

+ +

The {{jsxref("String")}} object is a wrapper around the string primitive data type.

+ +
const foo = new String('foo'); // Creates a String object
+console.log(foo); // Displays: [String: 'foo']
+typeof foo; // Returns 'object'
+
+ +

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal.

+ +

You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:

+ +
const firstString = '2 + 2'; // Creates a string literal value
+const secondString = new String('2 + 2'); // Creates a String object
+eval(firstString); // Returns the number 4
+eval(secondString); // Returns the string "2 + 2"
+ +

A String object has one property, length, that indicates the number of UTF-16 code units in the string. For example, the following code assigns helloLength the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects:

+ +
const hello = 'Hello, World!';
+const helloLength = hello.length;
+hello[0] = 'L'; // This has no effect, because strings are immutable
+hello[0]; // This returns "H"
+
+ +

Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.

+ +

A String object has a variety of methods: for example those that return a variation on the string itself, such as substring and toUpperCase.

+ +

The following table summarizes the methods of {{jsxref("String")}} objects.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Methods of String

+
MethodDescription
{{jsxref("String.charAt", "charAt")}}, {{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}}Return the character or character code at the specified position in string.
{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}}Return the position of specified substring in the string or last position of specified substring, respectively.
{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}}Returns whether or not the string starts, ends or contains a specified string.
{{jsxref("String.concat", "concat")}}Combines the text of two strings and returns a new string.
{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}}Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.
{{jsxref("String.split", "split")}}Splits a String object into an array of strings by separating the string into substrings.
{{jsxref("String.slice", "slice")}}Extracts a section of a string and returns a new string.
{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}}Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.
{{jsxref("String.match", "match")}}, {{jsxref("String.matchAll", "matchAll")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}}Work with regular expressions.
{{jsxref("String.toLowerCase", "toLowerCase")}}, {{jsxref("String.toUpperCase", "toUpperCase")}} +

Return the string in all lowercase or all uppercase, respectively.

+
{{jsxref("String.normalize", "normalize")}}Returns the Unicode Normalization Form of the calling string value.
{{jsxref("String.repeat", "repeat")}}Returns a string consisting of the elements of the object repeated the given times.
{{jsxref("String.trim", "trim")}}Trims whitespace from the beginning and end of the string.
+ +

Multi-line template literals

+ +

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

+ +

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}).

+ +

Multi-lines

+ +

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

+ +
console.log('string text line 1\n\
+string text line 2');
+// "string text line 1
+// string text line 2"
+ +

To get the same effect with multi-line strings, you can now write:

+ +
console.log(`string text line 1
+string text line 2`);
+// "string text line 1
+// string text line 2"
+ +

Embedded expressions

+ +

In order to embed expressions within normal strings, you would use the following syntax:

+ +
const five = 5;
+const ten = 10;
+console.log('Fifteen is ' + (five + ten) + ' and not ' + (2 * five + ten) + '.');
+// "Fifteen is 15 and not 20."
+ +

Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

+ +
const five = 5;
+const ten = 10;
+console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`);
+// "Fifteen is 15 and not 20."
+ +

For more information, read about Template literals in the JavaScript reference.

+ +

Internationalization

+ +

The {{jsxref("Intl")}} object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} objects are properties of the Intl object.

+ +

Date and time formatting

+ +

The {{jsxref("DateTimeFormat")}} object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.)

+ +
const msPerDay = 24 * 60 * 60 * 1000;
+
+// July 17, 2014 00:00:00 UTC.
+const july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));
+
+const options = { year: '2-digit', month: '2-digit', day: '2-digit',
+                hour: '2-digit', minute: '2-digit', timeZoneName: 'short' };
+const americanDateTime = new Intl.DateTimeFormat('en-US', options).format;
+
+console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
+
+ +

Number formatting

+ +

The {{jsxref("NumberFormat")}} object is useful for formatting numbers, for example currencies.

+ +
const gasPrice = new Intl.NumberFormat('en-US',
+                        { style: 'currency', currency: 'USD',
+                          minimumFractionDigits: 3 });
+
+console.log(gasPrice.format(5.259)); // $5.259
+
+const hanDecimalRMBInChina = new Intl.NumberFormat('zh-CN-u-nu-hanidec',
+                        { style: 'currency', currency: 'CNY' });
+
+console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五
+
+ +

Collation

+ +

The {{jsxref("Collator")}} object is useful for comparing and sorting strings.

+ +

For example, there are actually two different sort orders in German, phonebook and dictionary. Phonebook sort emphasizes sound, and it’s as if “ä”, “ö”, and so on were expanded to “ae”, “oe”, and so on prior to sorting.

+ +
const names = ['Hochberg', 'Hönigswald', 'Holzman'];
+
+const germanPhonebook = new Intl.Collator('de-DE-u-co-phonebk');
+
+// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
+console.log(names.sort(germanPhonebook.compare).join(', '));
+// logs "Hochberg, Hönigswald, Holzman"
+
+ +

Some German words conjugate with extra umlauts, so in dictionaries it’s sensible to order ignoring umlauts (except when ordering words differing only by umlauts: schon before schön).

+ +
const germanDictionary = new Intl.Collator('de-DE-u-co-dict');
+
+// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
+console.log(names.sort(germanDictionary.compare).join(', '));
+// nhật ký "Hồ Chí Minh, Holzman, Hönigswald"
+
+ +

Để biết thêm thông tin về API {{jsxref ("Intl")}}, xem thêm Giới thiệu API quốc tế hóa JavaScript .

+ +
+
+

{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}

+
+
diff --git a/files/bg/web/javascript/index.html b/files/bg/web/javascript/index.html new file mode 100644 index 0000000000..70e8bf97af --- /dev/null +++ b/files/bg/web/javascript/index.html @@ -0,0 +1,127 @@ +--- +title: JavaScript +slug: Web/JavaScript +tags: + - JavaScript + - Landing + - Learn + - NeedsTranslation + - TopicStub + - 'l10n:priority' +translation_of: Web/JavaScript +--- +
{{JsSidebar}}
+ +

JavaScript (JS) е лека интерпретация или JIT- компилиран програмен език с {{Glossary("First-class Function(Първокласни функции)", "първокласни функции")}}. Въпреки, че е най-добре познат като скриптов език за уеб страници , също така и много работни среди без браузър го използват. Такива като node.js, Apache CouchDB и Adobe Acrobat. JavaScript също е и {{Glossary("Прототипно базиран език за програмиране", "прототипно базиран")}}, използващ мулти-парадигма, динамичен език.  Поддържа обектно ориентирано програмиране , императивни и декларативни (функционално програмиране) стилове. Прочетете повече  за JavaScript.

+ +

Този раздел на сайта е посветен на самия език на JavaScript , и не съдържа части/информация,които са специфични за уеб страници или други хост среди.

+ +

За информация относно  {{Glossary("API","APIs")}} специфични за УЕБ страниците, моля вижте Web APIs или DOM.

+ +

Стандарта за JavaScript се нарича  ECMAScript. От  2012, всички модерни браузъри напълно поддържат ECMAScript 5.1. По-старите браузъри поддържат поне ECMAScript 3. На 17 Юни 2015 г. , ECMA International публикува шестата основна версия на ECMAScript, която и официално се нарича  ECMAScript 2015 и е първоначално наричана ECMAScript 6 или ES6. От тогава, ECMAScript стандартите се появяват на годишна база. Тази документация се отнася до най-новата версия на проекта, която понастоящем е ECMAScript 2018.

+ +

Не бъркайте JavaScript със  езика за програмиране Java. И двата езика "Java" и "JavaScript" са търговски марки или регистрирани търговски марки на Oracle в САЩ и други държави. И двата езика за програмиране имат много различен синтакс, семантика и изпозлване.

+ +
+
+

Уроци

+ +

Научете се как да програмирате с JavaScript чрез ръководства и уроци.

+ +

За напълно начианещи

+ +

Разгледайте темата  Lеearning Area JavaScript topic ако искате да учите JavaScript, но нямате предишен опит в JavaScript или програмирането. Пълните налични модули са както следва:

+ +
+
JavaScript първи стъпки
+
Отговори на някои основни въпроси като "Какво е JavaScript?", "Как изглежда?" И "какво може да направи?", Заедно с обсъждане на ключови характеристики на JavaScript, като променливи, низове, числа и масиви.
+
JavaScript изграждащи блокове
+
Продължава с нашето покритие за ключовите характеристики на Javascript, насочвайки вниманието ни към често срещаните типове блокове код, като условни изрази, цикли, функции и събития.
+
+ +

Javascript ръководство

+ +
+
JavaScript ръководство
+
Много по-подробно и детйално ръководство за езика JavaScript , насочено повече към хора с опит в програмирането или с друг език за програмиране.
+
+ +

Средно напреднали

+ +
+
Въведение в  JavaScript обектите
+
Обектно-ориентираният характер на Javascript e важен за разбиране, ако искате да стигнете по-далеч със знанията за езика и да пишете по-ефективен код. Затова сме Ви предоставили този модул , за да Ви помогне по-добре.
+
Уеб 'APIs' от страна на клиента
+
Когато пишете клиентски ориентиран JavaScript за уеб сайтове или приложения, няма да стигнете много далеч, преди да започнете да използвате API - интерфейси за манипулиране на различни аспекти на браузъра и операционната система на която сайтът работи, или дори данни от други уеб сайтове или услуги. В този модул ще разгледаме какво представляват API-тата и как да използваме някои от най-често използваните приложни програмни интерфейси(API), с които ще се сблъскате най-често в работата си .
+
+ +
+
Повторно въвеждане в  JavaScript
+
Преглед за тези, които мислят, че знаят повече за JavaScript.
+
+ +
+
Структори от данни в JavaScript
+
+
Преглед на наличните структури от данни в JavaScript.
+
+
Сравнение на равенството и еднаквостта
+
JavaScript осигурява три различни операции за сравнение на стойности: стриктно равенство, използвайки ===, свободно сравнение, използвайки ==, и метода {{jsxref("Global_Objects/Object/is", "Object.is()")}} .
+
+ +

Напреднали

+ +
+
Наследяване и прототипна верига
+
Обяснение на широко неразбраното и подценено прототипно-базирано наследяване.
+
Строг режим
+
Строгия режим дефинира/определя, че не можете да използвате която и да е променлива преди да я инициализирате/създадете. Това е ограничен вариант на ECMAScript 5 стандарта, за по-бърза работа и по-лесно остраняване на грешки(дебъгване).
+
JavaScript типизирани/типове масиви
+
Типизираните масиви в JavaScript предоставят механизъм за достъп до необработени двоични данни.
+
Управелние на паметта
+
Жизненият цикъл на паметта и събирането на "боклука" в Javascript.
+
Конкурентен модел и цикъл на събитията
+
JavaScript има конкурентен модел, който е  базиран на "цикъл на сибитията (event loop) ".
+
+
+ +
+

Препратка

+ +

Разгледайте пълната справочна документация на JavaScript.

+ +
+
Стандартни обекти
+
Запознайте се със стандартните вградени обекти {{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Error")}}, {{jsxref("Function")}}, {{jsxref("JSON")}}, {{jsxref("Math")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("RegExp")}}, {{jsxref("String")}}, {{jsxref("Map")}}, {{jsxref("Set")}}, {{jsxref("WeakMap")}}, {{jsxref("WeakSet")}}, and others.
+
Изрази и оператори
+
Научете повече за поведението на JavaScript операторите  {{jsxref("Оператори/instanceof", "instanceof")}}, {{jsxref("Оператори/typeof", "typeof")}}, {{jsxref("Оператори/new", "new")}}, {{jsxref("Оператори/this", "this")}}, оператора precedence, и още.
+
Изавления и декларации
+
Научете как {{jsxref("Изавления/do...while", "do-while")}}, {{jsxref("Изавления/for...in", "for-in")}}, {{jsxref("Изавления/for...of", "for-of")}}, {{jsxref("Изавления/try...catch", "try-catch")}}, {{jsxref("Изавления/let", "let")}}, {{jsxref("Изавления/var", "var")}}, {{jsxref("Изавления/const", "const")}}, {{jsxref("Изавления/if...else", "if-else")}}, {{jsxref("Изавления/switch", "switch")}}, и още JavaScript изавления и ключови думи за работа.
+
Функции
+
Научете се как да работите с JavaScript's функциите за разработване на вашите приложения.
+
+ +

Инструменти & ресурси

+ +

Полезни инструменти за писане и отстраняване на грешки във вашият JavaScript код.

+ +
+
Firefox Инструменти за Разработчици
+
Scratchpad, Web Console, JavaScript Profiler, Debugger, и още.
+
JavaScript Щитове
+
JavaScript щита позволява бързото тестване на откъси от JavaScript код.
+
TogetherJS
+
Сътрудничеството става лесно. Като добавите TogetherJS към сайта си, вашите потребители могат да си помагат един на друг в уебсайта ви и то в реално време!
+
Stack Overflow
+
Stack Overflow въпроси маркирани с "JavaScript".
+
JavaScript версии и бележки по изданието
+
Прегледайте последните истории свързани с JavaScript's и състоянието на изпълнение.
+
JSFiddle
+
Редактирай JavaScript, CSS, HTML и получете резултати на живо. Използвайте външни ресурси и сътрудничете с екипа си онлайн.
+
Plunker
+
+
Plunker е онлайн общност за създаване, сътрудничество и споделяне на идеи за уеб разработки. Редактирайте вашите JavaScript, CSS, HTML файлове и получете резултати на живо и структура на файла.
+
+
+
+
diff --git a/files/bg/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/bg/web/javascript/inheritance_and_the_prototype_chain/index.html new file mode 100644 index 0000000000..65194d2deb --- /dev/null +++ b/files/bg/web/javascript/inheritance_and_the_prototype_chain/index.html @@ -0,0 +1,563 @@ +--- +title: Inheritance and the prototype chain +slug: Web/JavaScript/Inheritance_and_the_prototype_chain +translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain +--- +
{{jsSidebar("Advanced")}}
+ +
+ +

JavaScript е малко объркващ за разработчиците с опит в езиците, базирани на класове (като Java или C ++), тъй като е динамичен и не осигурява реализация на клас сам по себе си (ключовата дума клас е въведена в ES2015, но е syntax sugar) и JavaScript остава прототипно базиран.

+ +

Когато става дума за наследяване, JavaScript има само една конструкция: обекти. Всеки обект има свойство, което съдържа връзка към друг обект, наречен негов прототип. Този прототип има собствен прототип и така нататък, докато прототипа не стане null. По дефиниция null няма прототип и действа като крайна връзка в тази верига на прототипа.

+ +

Nearly all objects in JavaScript are instances of {{jsxref("Object")}} which sits on the top of a prototype chain.

+ +

While this confusion is often considered to be one of JavaScript's weaknesses, the prototypal inheritance model itself is, in fact, more powerful than the classic model. It is, for example, fairly trivial to build a classic model on top of a prototypal model.

+ +

Inheritance with the prototype chain

+ +

Inheriting properties

+ +

JavaScript objects are dynamic "bags" of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

+ +
+

Following the ECMAScript standard, the notation someObject.[[Prototype]] is used to designate the prototype of someObject. Since ECMAScript 2015, the [[Prototype]] is accessed using the accessors {{jsxref("Object.getPrototypeOf()")}} and {{jsxref("Object.setPrototypeOf()")}}. This is equivalent to the JavaScript property __proto__ which is non-standard but de-facto implemented by many browsers.

+ +

It should not be confused with the func.prototype property of functions, which instead specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor. The Object.prototype property represents the {{jsxref("Object")}} prototype object.

+
+ +

Here is what happens when trying to access a property:

+ +
// Let's create an object o from function f with its own properties a and b:
+let f = function () {
+   this.a = 1;
+   this.b = 2;
+}
+let o = new f(); // {a: 1, b: 2}
+
+// add properties in f function's prototype
+f.prototype.b = 3;
+f.prototype.c = 4;
+
+// do not set the prototype f.prototype = {b:3,c:4}; this will break the prototype chain
+// o.[[Prototype]] has properties b and c.
+// o.[[Prototype]].[[Prototype]] is Object.prototype.
+// Finally, o.[[Prototype]].[[Prototype]].[[Prototype]] is null.
+// This is the end of the prototype chain, as null,
+// by definition, has no [[Prototype]].
+// Thus, the full prototype chain looks like:
+// {a: 1, b: 2} ---> {b: 3, c: 4} ---> Object.prototype ---> null
+
+console.log(o.a); // 1
+// Is there an 'a' own property on o? Yes, and its value is 1.
+
+console.log(o.b); // 2
+// Is there a 'b' own property on o? Yes, and its value is 2.
+// The prototype also has a 'b' property, but it's not visited.
+// This is called Property Shadowing
+
+console.log(o.c); // 4
+// Is there a 'c' own property on o? No, check its prototype.
+// Is there a 'c' own property on o.[[Prototype]]? Yes, its value is 4.
+
+console.log(o.d); // undefined
+// Is there a 'd' own property on o? No, check its prototype.
+// Is there a 'd' own property on o.[[Prototype]]? No, check its prototype.
+// o.[[Prototype]].[[Prototype]] is Object.prototype and there is no 'd' property by default, check its prototype.
+// o.[[Prototype]].[[Prototype]].[[Prototype]] is null, stop searching,
+// no property found, return undefined.
+
+ +

Code Link

+ +

Setting a property to an object creates an own property. The only exception to the getting and setting behavior rules is when there is an inherited property with a getter or a setter.

+ +

Inheriting "methods"

+ +

JavaScript does not have "methods" in the form that class-based languages define them. In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property, including property shadowing as shown above (in this case, a form of method overriding).

+ +

When an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

+ +
var o = {
+  a: 2,
+  m: function() {
+    return this.a + 1;
+  }
+};
+
+console.log(o.m()); // 3
+// When calling o.m in this case, 'this' refers to o
+
+var p = Object.create(o);
+// p is an object that inherits from o
+
+p.a = 4; // creates a property 'a' on p
+console.log(p.m()); // 5
+// when p.m is called, 'this' refers to p.
+// So when p inherits the function m of o,
+// 'this.a' means p.a, the property 'a' of p
+
+
+
+ +

Using prototypes in JavaScript

+ +

Let's look at what happens behind the scenes in a bit more detail.

+ +

In JavaScript, as mentioned above, functions are able to have properties. All functions have a special property named prototype. Please note that the code below is free-standing (it is safe to assume there is no other JavaScript on the webpage other than the below code). For the best learning experience, it is highly recommended that you open a console, navigate to the "console" tab, copy-and-paste in the below JavaScript code, and run it by pressing the Enter/Return key. (The console is included in most web browser's Developer Tools. More information is available for Firefox Developer Tools, Chrome DevTools, and Edge DevTools.)

+ +
function doSomething(){}
+console.log( doSomething.prototype );
+//  It does not matter how you declare the function, a
+//  function in JavaScript will always have a default
+//  prototype property.
+//  (Ps: There is one exception that arrow function doesn't have a default prototype property)
+var doSomething = function(){};
+console.log( doSomething.prototype );
+
+ +

As seen above, doSomething() has a default prototype property, as demonstrated by the console. After running this code, the console should have displayed an object that looks similar to this.

+ +
{
+    constructor: ƒ doSomething(),
+    __proto__: {
+        constructor: ƒ Object(),
+        hasOwnProperty: ƒ hasOwnProperty(),
+        isPrototypeOf: ƒ isPrototypeOf(),
+        propertyIsEnumerable: ƒ propertyIsEnumerable(),
+        toLocaleString: ƒ toLocaleString(),
+        toString: ƒ toString(),
+        valueOf: ƒ valueOf()
+    }
+}
+ +

We can add properties to the prototype of doSomething(), as shown below.

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar";
+console.log( doSomething.prototype );
+ +

This results in:

+ +
{
+    foo: "bar",
+    constructor: ƒ doSomething(),
+    __proto__: {
+        constructor: ƒ Object(),
+        hasOwnProperty: ƒ hasOwnProperty(),
+        isPrototypeOf: ƒ isPrototypeOf(),
+        propertyIsEnumerable: ƒ propertyIsEnumerable(),
+        toLocaleString: ƒ toLocaleString(),
+        toString: ƒ toString(),
+        valueOf: ƒ valueOf()
+    }
+}
+
+ +

We can now use the new operator to create an instance of doSomething() based on this prototype. To use the new operator, simply call the function normally except prefix it with new. Calling a function with the new operator returns an object that is an instance of the function. Properties can then be added onto this object.

+ +

Try the following code:

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar"; // add a property onto the prototype
+var doSomeInstancing = new doSomething();
+doSomeInstancing.prop = "some value"; // add a property onto the object
+console.log( doSomeInstancing );
+ +

This results in an output similar to the following:

+ +
{
+    prop: "some value",
+    __proto__: {
+        foo: "bar",
+        constructor: ƒ doSomething(),
+        __proto__: {
+            constructor: ƒ Object(),
+            hasOwnProperty: ƒ hasOwnProperty(),
+            isPrototypeOf: ƒ isPrototypeOf(),
+            propertyIsEnumerable: ƒ propertyIsEnumerable(),
+            toLocaleString: ƒ toLocaleString(),
+            toString: ƒ toString(),
+            valueOf: ƒ valueOf()
+        }
+    }
+}
+ +

As seen above, the __proto__ of doSomeInstancing is doSomething.prototype. But, what does this do? When you access a property of doSomeInstancing, the browser first looks to see if doSomeInstancing has that property.

+ +

If doSomeInstancing does not have the property, then the browser looks for the property in the __proto__ of doSomeInstancing (a.k.a. doSomething.prototype). If the __proto__ of doSomeInstancing has the property being looked for, then that property on the __proto__ of doSomeInstancing is used.

+ +

Otherwise, if the __proto__ of doSomeInstancing does not have the property, then the __proto__ of the __proto__ of doSomeInstancing is checked for the property. By default, the __proto__ of any function's prototype property is window.Object.prototype. So, the __proto__ of the __proto__ of doSomeInstancing (a.k.a. the __proto__ of doSomething.prototype (a.k.a. Object.prototype)) is then looked through for the property being searched for.

+ +

If the property is not found in the __proto__ of the __proto__ of doSomeInstancing, then the __proto__ of the __proto__ of the __proto__ of doSomeInstancing is looked through. However, there is a problem: the __proto__ of the __proto__ of the __proto__ of doSomeInstancing does not exist. Then, and only then, after the entire prototype chain of __proto__'s is looked through, and there are no more __proto__s does the browser assert that the property does not exist and conclude that the value at the property is undefined.

+ +

Let's try entering some more code into the console:

+ +
function doSomething(){}
+doSomething.prototype.foo = "bar";
+var doSomeInstancing = new doSomething();
+doSomeInstancing.prop = "some value";
+console.log("doSomeInstancing.prop:      " + doSomeInstancing.prop);
+console.log("doSomeInstancing.foo:       " + doSomeInstancing.foo);
+console.log("doSomething.prop:           " + doSomething.prop);
+console.log("doSomething.foo:            " + doSomething.foo);
+console.log("doSomething.prototype.prop: " + doSomething.prototype.prop);
+console.log("doSomething.prototype.foo:  " + doSomething.prototype.foo);
+ +

This results in the following:

+ +
doSomeInstancing.prop:      some value
+doSomeInstancing.foo:       bar
+doSomething.prop:           undefined
+doSomething.foo:            undefined
+doSomething.prototype.prop: undefined
+doSomething.prototype.foo:  bar
+ +

Different ways to create objects and the resulting prototype chain

+ +

Objects created with syntax constructs

+ +
var o = {a: 1};
+
+// The newly created object o has Object.prototype as its [[Prototype]]
+// o has no own property named 'hasOwnProperty'
+// hasOwnProperty is an own property of Object.prototype.
+// So o inherits hasOwnProperty from Object.prototype
+// Object.prototype has null as its prototype.
+// o ---> Object.prototype ---> null
+
+var b = ['yo', 'whadup', '?'];
+
+// Arrays inherit from Array.prototype
+// (which has methods indexOf, forEach, etc.)
+// The prototype chain looks like:
+// b ---> Array.prototype ---> Object.prototype ---> null
+
+function f() {
+  return 2;
+}
+
+// Functions inherit from Function.prototype
+// (which has methods call, bind, etc.)
+// f ---> Function.prototype ---> Object.prototype ---> null
+
+ +

With a constructor

+ +

A "constructor" in JavaScript is "just" a function that happens to be called with the new operator.

+ +
function Graph() {
+  this.vertices = [];
+  this.edges = [];
+}
+
+Graph.prototype = {
+  addVertex: function(v) {
+    this.vertices.push(v);
+  }
+};
+
+var g = new Graph();
+// g is an object with own properties 'vertices' and 'edges'.
+// g.[[Prototype]] is the value of Graph.prototype when new Graph() is executed.
+
+ +

With Object.create

+ +

ECMAScript 5 introduced a new method: {{jsxref("Object.create()")}}. Calling this method creates a new object. The prototype of this object is the first argument of the function:

+ +
var a = {a: 1};
+// a ---> Object.prototype ---> null
+
+var b = Object.create(a);
+// b ---> a ---> Object.prototype ---> null
+console.log(b.a); // 1 (inherited)
+
+var c = Object.create(b);
+// c ---> b ---> a ---> Object.prototype ---> null
+
+var d = Object.create(null);
+// d ---> null
+console.log(d.hasOwnProperty);
+// undefined, because d doesn't inherit from Object.prototype
+
+ +

delete Operator with Object.create and new operator

+ +

Using Object.create of another object demonstrates prototypical inheritance with the delete operation:

+ +
var a = {a: 1};
+
+var b = Object.create(a);
+
+console.log(a.a); // print 1
+console.log(b.a); // print 1
+b.a=5;
+console.log(a.a); // print 1
+console.log(b.a); // print 5
+delete b.a;
+console.log(a.a); // print 1
+console.log(b.a); // print 1(b.a value 5 is deleted but it showing value from its prototype chain)
+delete a.a;
+console.log(a.a); // print undefined
+console.log(b.a); // print undefined
+ +

The new operator has a shorter chain in this example:

+ +
function Graph() {
+  this.vertices = [4,4];
+}
+
+var g = new Graph();
+console.log(g.vertices); // print [4,4]
+g.vertices = 25;
+console.log(g.vertices); // print 25
+delete g.vertices;
+console.log(g.vertices); // print undefined
+
+ +

With the class keyword

+ +

ECMAScript 2015 introduced a new set of keywords implementing classes. The new keywords include {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}}, {{jsxref("Classes/static", "static")}}, {{jsxref("Classes/extends", "extends")}}, and {{jsxref("Operators/super", "super")}}.

+ +
'use strict';
+
+class Polygon {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+
+class Square extends Polygon {
+  constructor(sideLength) {
+    super(sideLength, sideLength);
+  }
+  get area() {
+    return this.height * this.width;
+  }
+  set sideLength(newLength) {
+    this.height = newLength;
+    this.width = newLength;
+  }
+}
+
+var square = new Square(2);
+
+ +

Performance

+ +

The lookup time for properties that are high up on the prototype chain can have a negative impact on the performance, and this may be significant in the code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.

+ +

Also, when iterating over the properties of an object, every enumerable property that is on the prototype chain will be enumerated. To check whether an object has a property defined on itself and not somewhere on its prototype chain, it is necessary to use the hasOwnProperty method which all objects inherit from Object.prototype. To give you a concrete example, let's take the above graph example code to illustrate it:

+ +
console.log(g.hasOwnProperty('vertices'));
+// true
+
+console.log(g.hasOwnProperty('nope'));
+// false
+
+console.log(g.hasOwnProperty('addVertex'));
+// false
+
+console.log(g.__proto__.hasOwnProperty('addVertex'));
+// true
+
+ +

hasOwnProperty is the only thing in JavaScript which deals with properties and does not traverse the prototype chain.

+ +

Note: It is not enough to check whether a property is undefined. The property might very well exist, but its value just happens to be set to undefined.

+ +

Bad practice: Extension of native prototypes

+ +

One misfeature that is often used is to extend Object.prototype or one of the other built-in prototypes.

+ +

This technique is called monkey patching and breaks encapsulation. While used by popular frameworks such as Prototype.js, there is still no good reason for cluttering built-in types with additional non-standard functionality.

+ +

The only good reason for extending a built-in prototype is to backport the features of newer JavaScript engines, like Array.forEach.

+ +

Summary of methods for extending the prototype chain

+ +

Here are all 4 ways and their pros/cons. All of the examples listed below create exactly the same resulting inst object (thus logging the same results to the console), except in different ways for the purpose of illustration.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameExample(s)Pro(s)Con(s)
New-initialization +
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto = new foo;
+proto.bar_prop = "bar val";
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop);
+
+
Supported in every browser imaginable (support goes all the way back to IE 5.5!). Also, it is very fast, very standard, and very JIST-optimizable.In order to use this method, the function in question must be initialized. During this initialization, the constructor may store unique information that must be generated per-object. However, this unique information would only be generated once, potentially leading to problems. Additionally, the initialization of the constructor may put unwanted methods onto the object. However, both these are generally not problems at all (in fact, usually beneficial) if it is all your own code and you know what does what where.
Object.create +
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto = Object.create(
+  foo.prototype
+);
+proto.bar_prop = "bar val";
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop);
+
+ +
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto = Object.create(
+  foo.prototype,
+  {
+    bar_prop: {
+      value: "bar val"
+    }
+  }
+);
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop)
+
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the direct setting of __proto__ in a way that is one-time-only so that the browser can better optimize the object. Also allows the creation of objects without a prototype via Object.create(null).Not supported in IE8 and below. However, as Microsoft has discontinued extended support for systems running these old browsers, this should not be a concern for most applications. Additionally, the slow object initialization can be a performance black hole if using the second argument because each object-descriptor property has its own separate descriptor object. When dealing with hundreds of thousands of object descriptors in the form of object, there can arise a serious issue with lag.
+

Object.setPrototypeOf

+
+
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto = {
+  bar_prop: "bar val"
+};
+Object.setPrototypeOf(
+  proto, foo.prototype
+);
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop);
+
+ +
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto;
+proto=Object.setPrototypeOf(
+  { bar_prop: "bar val" },
+  foo.prototype
+);
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop)
+
Support in all in-use-today browsers which are all non-microsoft browsers plus IE9 and up. Allows the dynamic manipulation of an objects prototype and can even force a prototype on a prototype-less object created with Object.create(null).Should-be-deprecated and ill-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE8 and below.
__proto__ +
+function foo(){}
+foo.prototype = {
+  foo_prop: "foo val"
+};
+function bar(){}
+var proto = {
+  bar_prop: "bar val",
+  __proto__: foo.prototype
+};
+bar.prototype = proto;
+var inst = new bar;
+console.log(inst.foo_prop);
+console.log(inst.bar_prop);
+
+ +
+var inst = {
+  __proto__: {
+    bar_prop: "bar val",
+    __proto__: {
+      foo_prop: "foo val",
+      __proto__: Object.prototype
+    }
+  }
+};
+console.log(inst.foo_prop);
+console.log(inst.bar_prop)
+
Support in all in-use-today browsers which are all non-microsoft browsers plus IE11 and up. Setting __proto__ to something that is not an object only fails silently. It does not throw an exception.Grossly deprecated and non-performant. Making your Javascript run fast is completely out of the question if you dare use this in the final production code because many browsers optimize the prototype and try to guess the location of the method in the memory when calling an instance in advance, but setting the prototype dynamically disrupts all these optimizations and can even force some browsers to recompile for deoptimization your code just to make it work according to the specs. Not supported in IE10 and below.
+ +

prototype and Object.getPrototypeOf

+ +

JavaScript is a bit confusing for developers coming from Java or C++, as it's all dynamic, all runtime, and it has no classes at all. It's all just instances (objects). Even the "classes" we simulate are just a function object.

+ +

You probably already noticed that our function A has a special property called prototype. This special property works with the JavaScript new operator. The reference to the prototype object is copied to the internal [[Prototype]] property of the new instance. For example, when you do var a1 = new A(), JavaScript (after creating the object in memory and before running function A() with this defined to it) sets a1.[[Prototype]] = A.prototype. When you then access properties of the instance, JavaScript first checks whether they exist on that object directly, and if not, it looks in [[Prototype]]. This means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the changes appear in all existing instances, if you wanted to.

+ +

If, in the example above, you do var a1 = new A(); var a2 = new A(); then a1.doSomething would actually refer to Object.getPrototypeOf(a1).doSomething, which is the same as the A.prototype.doSomething you defined, i.e. Object.getPrototypeOf(a1).doSomething == Object.getPrototypeOf(a2).doSomething == A.prototype.doSomething.

+ +

In short, prototype is for types, while Object.getPrototypeOf() is the same for instances.

+ +

[[Prototype]] is looked at recursively, i.e. a1.doSomething, Object.getPrototypeOf(a1).doSomething, Object.getPrototypeOf(Object.getPrototypeOf(a1)).doSomething etc., until it's found or Object.getPrototypeOf returns null.

+ +

So, when you call

+ +
var o = new Foo();
+ +

JavaScript actually just does

+ +
var o = new Object();
+o.[[Prototype]] = Foo.prototype;
+Foo.call(o);
+ +

(or something like that) and when you later do

+ +
o.someProp;
+ +

it checks whether o has a property someProp. If not, it checks Object.getPrototypeOf(o).someProp, and if that doesn't exist it checks Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp, and so on.

+ +

In conclusion

+ +

It is essential to understand the prototypal inheritance model before writing complex code that makes use of it. Also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. Further, the native prototypes should never be extended unless it is for the sake of compatibility with newer JavaScript features.

diff --git a/files/bg/web/javascript/reference/classes/constructor/index.html b/files/bg/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..4d3971672e --- /dev/null +++ b/files/bg/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,130 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - Класове + - Конструктор +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +

Методът constructor е специален метод за създаване и инициализиране на обект , създаден в рамките класът (class).

+ +
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
+ + + +

Синтаксис

+ +
constructor([arguments]) { ... }
+ +

Описание

+ +

Може да има само един специален метод с име "constructor" в даден клас (class). Ако има повече от един метод с името constructor в класът си , ще се появи грешка   {{jsxref("SyntaxError")}}.

+ +

Конструктора (constructor) може да използва ключовата дума super за да извика конструктора на родителския клас.

+ +

Ако не посочите метода конструктор, ще се използва конструктор по подразбиране

+ +

Примери

+ +

Използване на метода  constructor

+ +

Този примерен код е взет от  classes sample (демо на живо).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Here, it calls the parent class' constructor with lengths
+    // provided for the Polygon's width and height
+    super(length, length);
+    // Note: In derived classes, super() must be called before you
+    // can use 'this'. Leaving this out will cause a reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

Друг пример

+ +

Разгледайте този код :

+ +
class Polygon {
+    constructor() {
+        this.name = "Polygon";
+    }
+}
+
+class Square extends Polygon {
+    constructor() {
+        super();
+    }
+}
+
+class Rectangle {}
+
+Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
+
+console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
+console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
+
+let newInstance = new Square();
+console.log(newInstance.name); //Polygon
+ +

Тук прототипа на класът Square се променя, но все пак конструктора на предишния базов клас Polygon се извиква, когато се създава нова инстанция(екземлпяр) от класът Square. Това е така , защото в класът Squre използваме ключовата дума super, извиквайки конструктора на родителският клас Polygon .

+ +

Конструктор по подразбиране

+ +

Както е посочено,ако не посочите метод конструктор, ще се използва  конструктор по подразбиране . За базовите класове , конструктора по подразбиране е :

+ +
constructor() {}
+
+ +

За производни класове, конструктора по подразбиране е :

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
+ +

Съвместимост с браузъра

+ + + +

{{Compat("javascript.classes.constructor")}}

+ +

Въжте също

+ + diff --git a/files/bg/web/javascript/reference/classes/extends/index.html b/files/bg/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..940e815d6c --- /dev/null +++ b/files/bg/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,112 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - JavaScript наследяване + - Класове + - наследяване +translation_of: Web/JavaScript/Reference/Classes/extends +--- +
{{jsSidebar("Classes")}}
+ +

Ключовата дума extends се използва в  декларацията на класове или класовите изрази за създаване на клас, който е дете на друг клас.

+ +
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
+ + + +

Синтаксис

+ +
class ChildClass extends ParentClass { ... }
+ +

Описание

+ +

Ключовата дума extends може да бъде използвана като подклас на потребителски класове, както и за вградени обекти.

+ +

Прототипът (.prototype) на разширението трябва да е  {{jsxref("Object")}} или {{jsxref("null")}}.

+ +

Примери

+ +

Използване на  extends

+ +

Първият пример създава клас, наречен Square от клас, наречен Polygon (Square класът наследява клас Polygon ). Този пример е взет от това демо на живо (източник).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Here, it calls the parent class' constructor with lengths
+    // provided for the Polygon's width and height
+    super(length, length);
+    // Note: In derived classes, super() must be called before you
+    // can use 'this'. Leaving this out will cause a reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+}
+ +

Използване на  extends с вградени обекти

+ +

Този пример разширява вграденият {{jsxref("Date")}} обект. Този пример е взет от това демо на живо (източник).

+ +
class myDate extends Date {
+  constructor() {
+    super();
+  }
+
+  getFormattedDate() {
+    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
+  }
+}
+ +

Наследяване на  null

+ +

Наследяване от {{jsxref("null")}} работи както при нормалните класове, eс изключение на това , че обектът на прототипа не наследява от {{jsxref("Object.prototype")}}.

+ +
class nullExtends extends null {
+  constructor() {}
+}
+
+Object.getPrototypeOf(nullExtends); // Function.prototype
+Object.getPrototypeOf(nullExtends.prototype) // null
+
+new nullExtends(); //ReferenceError: this is not defined
+
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + +
СпецификацииСтатусКоментар
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
+ +

Съвместимост с браузъра

+ + + +

{{Compat("javascript.classes.extends")}}

+ +

Вижте още

+ + diff --git a/files/bg/web/javascript/reference/classes/index.html b/files/bg/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..dc88fc8548 --- /dev/null +++ b/files/bg/web/javascript/reference/classes/index.html @@ -0,0 +1,431 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript 2015 + - Inheritance + - Intermediate + - JavaScript + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +
{{JsSidebar("Classes")}}
+ +

JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.

+ +

Defining classes

+ +

Classes are in fact "special functions", and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.

+ +

Class declarations

+ +

One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Rectangle" here).

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Hoisting

+ +

An important difference between function declarations and class declarations is that function declarations are {{Glossary("Hoisting", "hoisted")}} and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a {{jsxref("ReferenceError")}}:

+ +
const p = new Rectangle(); // ReferenceError
+
+class Rectangle {}
+
+ +

Class expressions

+ +

A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) {{jsxref("Function.name", "name")}} property, though).

+ +
// unnamed
+let Rectangle = class {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle"
+
+// named
+let Rectangle = class Rectangle2 {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+};
+console.log(Rectangle.name);
+// output: "Rectangle2"
+
+ +
+

Note: Class expressions are subject to the same hoisting restrictions as described in the {{anch("Class declarations")}} section.

+
+ +

Class body and method definitions

+ +

The body of a class is the part that is in curly brackets {}. This is where you define class members, such as methods or constructor.

+ +

Strict mode

+ +

The body of a class is executed in strict mode, i.e., code written here is subject to stricter syntax for increased performance, some otherwise silent errors will be thrown, and certain keywords are reserved for future versions of ECMAScript.

+ +

Constructor

+ +

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A {{jsxref("SyntaxError")}} will be thrown if the class contains more than one occurrence of a constructor method.

+ +

A constructor can use the super keyword to call the constructor of the super class.

+ +

Prototype methods

+ +

See also method definitions.

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+  // Getter
+  get area() {
+    return this.calcArea();
+  }
+  // Method
+  calcArea() {
+    return this.height * this.width;
+  }
+}
+
+const square = new Rectangle(10, 10);
+
+console.log(square.area); // 100
+ +

Static methods

+ +

The static keyword defines a static method for a class. Static methods are called without instantiating their class and cannot be called through a class instance. Static methods are often used to create utility functions for an application.

+ +
class Point {
+  constructor(x, y) {
+    this.x = x;
+    this.y = y;
+  }
+
+  static distance(a, b) {
+    const dx = a.x - b.x;
+    const dy = a.y - b.y;
+
+    return Math.hypot(dx, dy);
+  }
+}
+
+const p1 = new Point(5, 5);
+const p2 = new Point(10, 10);
+
+console.log(Point.distance(p1, p2)); // 7.0710678118654755
+ +

Boxing with prototype and static methods

+ +

When a static or prototype method is called without a value for this, the this value will be undefined inside the method. This behavior will be the same even if the "use strict" directive isn't present, because code within the class body's syntactic boundary is always executed in strict mode.

+ +
class Animal {
+  speak() {
+    return this;
+  }
+  static eat() {
+    return this;
+  }
+}
+
+let obj = new Animal();
+obj.speak(); // Animal {}
+let speak = obj.speak;
+speak(); // undefined
+
+Animal.eat() // class Animal
+let eat = Animal.eat;
+eat(); // undefined
+ +

If the above is written using traditional function-based syntax, then autoboxing in method calls will happen in non–strict mode based on the initial this value. If the initial value is undefinedthis will be set to the global object.

+ +

Autoboxing will not happen in strict mode, the this value remains as passed.

+ +
function Animal() { }
+
+Animal.prototype.speak = function() {
+  return this;
+}
+
+Animal.eat = function() {
+  return this;
+}
+
+let obj = new Animal();
+let speak = obj.speak;
+speak(); // global object
+
+let eat = Animal.eat;
+eat(); // global object
+
+ +

Instance properties

+ +

Instance properties must be defined inside of class methods:

+ +
class Rectangle {
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+ +

Static class-side properties and prototype data properties must be defined outside of the ClassBody declaration:

+ +
Rectangle.staticWidth = 20;
+Rectangle.prototype.prototypeWidth = 25;
+
+ +

Field declarations

+ +
+

Public and private field declarations are an experimental feature (stage 3) proposed at TC39, the JavaScript standards committee. Support in browsers is limited, but the feature can be used through a build step with systems like Babel.

+
+ +

Public field declarations

+ +

With the JavaScript field declaration syntax, the above example can be written as:

+ +
class Rectangle {
+  height = 0;
+  width;
+  constructor(height, width) {
+    this.height = height;
+    this.width = width;
+  }
+}
+
+ +

By declaring fields up-front, class definitions become more self-documenting, and the fields are always present.

+ +

As seen above, the fields can be declared with or without a default value.

+ +

Private field declarations

+ +

Using private fields, the definition can be refined as below.

+ +
class Rectangle {
+  #height = 0;
+  #width;
+  constructor(height, width) {
+    this.#height = height;
+    this.#width = width;
+  }
+}
+
+ +

It's an error to reference private fields from outside of the class; they can only be read or written within the class body. By defining things which are not visible outside of the class, you ensure that your classes' users can't depend on internals, which may change version to version.

+ +
+

Private fields can only be declared up-front in a field declaration.

+
+ +

Private fields cannot be created later through assigning to them, the way that normal properties can.

+ +

 

+ +

Sub classing with extends

+ +

The extends keyword is used in class declarations or class expressions to create a class as a child of another class.

+ +
class Animal {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+}
+
+class Dog extends Animal {
+  constructor(name) {
+    super(name); // call the super class constructor and pass in the name parameter
+  }
+
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

If there is a constructor present in the subclass, it needs to first call super() before using "this".

+ +

One may also extend traditional function-based "classes":

+ +
function Animal (name) {
+  this.name = name;
+}
+
+Animal.prototype.speak = function () {
+  console.log(this.name + ' makes a noise.');
+}
+
+class Dog extends Animal {
+  speak() {
+    console.log(this.name + ' barks.');
+  }
+}
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie barks.
+
+ +

Note that classes cannot extend regular (non-constructible) objects. If you want to inherit from a regular object, you can instead use {{jsxref("Object.setPrototypeOf()")}}:

+ +
const Animal = {
+  speak() {
+    console.log(this.name + ' makes a noise.');
+  }
+};
+
+class Dog {
+  constructor(name) {
+    this.name = name;
+  }
+}
+
+// If you do not do this you will get a TypeError when you invoke speak
+Object.setPrototypeOf(Dog.prototype, Animal);
+
+let d = new Dog('Mitzie');
+d.speak(); // Mitzie makes a noise.
+
+ +

Species

+ +

You might want to return {{jsxref("Array")}} objects in your derived array class MyArray. The species pattern lets you override default constructors.

+ +

For example, when using methods such as {{jsxref("Array.map", "map()")}} that returns the default constructor, you want these methods to return a parent Array object, instead of the MyArray object. The {{jsxref("Symbol.species")}} symbol lets you do this:

+ +
class MyArray extends Array {
+  // Overwrite species to the parent Array constructor
+  static get [Symbol.species]() { return Array; }
+}
+
+let a = new MyArray(1,2,3);
+let mapped = a.map(x => x * x);
+
+console.log(mapped instanceof MyArray); // false
+console.log(mapped instanceof Array);   // true
+
+ +

Super class calls with super

+ +

The super keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance.

+ +
class Cat {
+  constructor(name) {
+    this.name = name;
+  }
+
+  speak() {
+    console.log(`${this.name} makes a noise.`);
+  }
+}
+
+class Lion extends Cat {
+  speak() {
+    super.speak();
+    console.log(`${this.name} roars.`);
+  }
+}
+
+let l = new Lion('Fuzzy');
+l.speak();
+// Fuzzy makes a noise.
+// Fuzzy roars.
+
+ +

Mix-ins

+ +

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

+ +

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

+ +
let calculatorMixin = Base => class extends Base {
+  calc() { }
+};
+
+let randomizerMixin = Base => class extends Base {
+  randomize() { }
+};
+
+ +

A class that uses these mix-ins can then be written like this:

+ +
class Foo { }
+class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}} 
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}} 
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.classes")}}

+ +

Running in Scratchpad

+ +

A class can't be redefined. If you're playing with code in Scratchpad (Firefox menu Tools > Web Developer > Scratchpad) and you 'Run' a definition of a class with the same name twice, you'll get a confusing SyntaxError: redeclaration of let <class-name>.

+ +

To re-run a definition, use Scratchpad's menu Execute > Reload and Run.
+ Please vote for bug #1428672.

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/classes/static/index.html b/files/bg/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..971bf40345 --- /dev/null +++ b/files/bg/web/javascript/reference/classes/static/index.html @@ -0,0 +1,135 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - Класове + - Статичен + - статичен метод +translation_of: Web/JavaScript/Reference/Classes/static +--- +
{{jsSidebar("Classes")}}
+ +

Ключовата дума static дефинира статичен метод за клас. Static methods aren't called on instances of the class. Instead, they're called on the class itself. Това често са помощни функции, като например функции за създаване или клониране на обекти.

+ +
{{EmbedInteractiveExample("pages/js/classes-static.html")}}
+ + + +

Синтаксис

+ +
static methodName() { ... }
+ +

Описание

+ +

Статичните методи се правят директно в класът и не могат да се извикват като инстанции на клас.

+ +

Извикване на статичен метод

+ +

От друг статичен метод

+ +

За да извикате статичен метод в рамките на друг статичен метод от същия клас, може да използвате ключовата дума this.

+ +
class StaticMethodCall {
+  static staticMethod() {
+    return 'Static method has been called';
+  }
+  static anotherStaticMethod() {
+    return this.staticMethod() + ' from another static method';
+  }
+}
+StaticMethodCall.staticMethod();
+// 'Static method has been called'
+
+StaticMethodCall.anotherStaticMethod();
+// 'Static method has been called from another static method'
+ +

От конструктора на клас и други методи

+ +

Статичните методи не са пряко достъпни, когато се използва ключовата дума this от нестатични методи. Трябва да ги извикате, използвайки името на класа: CLASSNAME.STATIC_METHOD_NAME() или да извикате метода като собственост на constructorthis.constructor.STATIC_METHOD_NAME().

+ +
class StaticMethodCall {
+  constructor() {
+    console.log(StaticMethodCall.staticMethod());
+    // 'static method has been called.'
+
+    console.log(this.constructor.staticMethod());
+    // 'static method has been called.'
+  }
+
+  static staticMethod() {
+    return 'static method has been called.';
+  }
+}
+ +

Примери

+ +

Следният пример показва няколко неща:

+ +
    +
  1. Как статичните методи се изпълняват в класът.
  2. +
  3. Това , че клас със статичен член може да бъде под-класиран.
  4. +
  5. Как статичният метод може и не може да бъде извикан.
  6. +
+ +
class Triple {
+  static triple(n) {
+    if (n === undefined) {
+      n = 1;
+    }
+    return n * 3;
+  }
+}
+
+class BiggerTriple extends Triple {
+  static triple(n) {
+    return super.triple(n) * super.triple(n);
+  }
+}
+
+console.log(Triple.triple());        // 3
+console.log(Triple.triple(6));       // 18
+
+var tp = new Triple();
+
+console.log(BiggerTriple.triple(3));
+// 81 (not affected by parent's instantiation)
+
+console.log(tp.triple());
+// 'tp.triple is not a function'.
+
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + +
СпецификацииСтатусКоментар
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}} 
+ +

Съвместимост с браузера

+ + + +

{{Compat("javascript.classes.static")}}

+ +

Вижте още

+ + diff --git a/files/bg/web/javascript/reference/errors/index.html b/files/bg/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..c295fccea6 --- /dev/null +++ b/files/bg/web/javascript/reference/errors/index.html @@ -0,0 +1,31 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Debugging + - Error + - Errors + - Exception + - JavaScript + - NeedsTranslation + - TopicStub + - exceptions +translation_of: Web/JavaScript/Reference/Errors +--- +

{{jsSidebar("Errors")}}

+ +

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

+ +

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

+ +

List of errors

+ +

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

+ +

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/errors/unexpected_type/index.html b/files/bg/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..372560f00e --- /dev/null +++ b/files/bg/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,70 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - JavaScript + - TypeError + - Грешки +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +
{{jsSidebar("Errors")}}
+ +

Съобщение

+ +
TypeError: "x" is (not) "y"
+
+Примери:
+TypeError: "x" is undefined
+TypeError: "x" is null
+TypeError: "undefined" is not an object
+TypeError: "x" is not an object or null
+TypeError: "x" is not a symbol
+
+ +

Вид на грешката

+ +

{{jsxref("TypeError")}}.

+ +

Какво се обърка?

+ +

Върнатият тип не отговаря на очакванията. Това се случва често при върната стойност {{jsxref("undefined")}} или {{jsxref("null")}}.

+ +

Някои методи като {{jsxref("Object.create()")}} или {{jsxref("Symbol.keyFor()")}} освен това изискват да им бъде предоставен определен тип.

+ +

Примери

+ +

Случаи, предизвикващи грешката

+ +
// Случаи, при които методът substring няма да работи.
+// Такива са undefined и null.
+var foo = undefined;
+foo.substring(1); // TypeError: foo is undefined
+
+var foo = null;
+foo.substring(1); // TypeError: foo is null
+
+
+// Методи, които очакват да бъдат извикани
+// върху точно определен тип.
+var foo = {}
+Symbol.keyFor(foo); // TypeError: foo is not a symbol
+
+var foo = 'bar'
+Object.create(foo); // TypeError: "foo" is not an object or null
+
+ +

Поправяне на грешката

+ +

За да оправите грешката в случай на указател, сочещ към стойност undefined или null, можете да използвате оператора typeof.

+ +
if (typeof foo !== 'undefined') {
+  // Сега знаем, че foo има определена стойност
+  // и можем да продължим.
+}
+ +

Вижте също

+ + diff --git a/files/bg/web/javascript/reference/functions/arrow_functions/index.html b/files/bg/web/javascript/reference/functions/arrow_functions/index.html new file mode 100644 index 0000000000..f2efe8ec10 --- /dev/null +++ b/files/bg/web/javascript/reference/functions/arrow_functions/index.html @@ -0,0 +1,394 @@ +--- +title: Arrow functions +slug: Web/JavaScript/Reference/Functions/Arrow_functions +tags: + - Средно напреднали + - Функции + - Функции със стрелка + - референция +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +
{{jsSidebar("Functions")}}
+ +

Функционалният израз със стрелка има по-кратък синтаксис, отколкото стандартното дефиниране на функция и няма свой собствен this, arguments, super, или new.target. Тези функции не са подходящи за изполване като метод функции(methods) и не могат да бъдат използвани като конструктори.

+ +
{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}
+ +

Синтаксис

+ +

Основен синтаксис

+ +
(param1, param2, …, paramN) => { statements }
+(param1, param2, …, paramN) => expression
+// равнозначно на: => { return expression; }
+
+// Скобите не са задължителни, когато има само един входен параметър:
+(singleParam) => { statements }
+singleParam => { statements }
+
+// Списъка с аргументи за функции без аргументи трябва да бъде написан, като се използват скоби.
+() => { statements }
+
+ +

Напреднал синтаксис

+ +
// Резултата може да бъде ограден в скоби за да бъде върнат под формата на обект(object literal expression):
+params => ({foo: bar})
+
+// Поддържат се Rest оператора и параметри по подразбиране
+(param1, param2, ...rest) => { statements }
+(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
+statements }
+
+// Деструктуриране на списъка с входни аргументи също се поддържа
+var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
+f(); // 6
+
+ +

Описание

+ +

Вижте също "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

+ +

Два фактора повлияха за въвеждането на функциите със стрелка: по-къси функции и липсата на ключовата дума this.

+ +

По-кракти функции

+ +
var elements = [
+  'Hydrogen',
+  'Helium',
+  'Lithium',
+  'Beryllium'
+];
+
+elements.map(function(element) {
+  return element.length;
+}); // извикването на описания код ще върне следния масив: [8, 6, 7, 9]
+
+// Горе описаната функция може да бъде написана и като функция със стрелка по следния начин
+elements.map((element) => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// Когато има само един входен параметър можем да премахнем скобите:
+elements.map(element => {
+  return element.length;
+}); // [8, 6, 7, 9]
+
+// Когато единственото нещо в функцията е връщане на резултат, можем да премахнем `return`
+//  и също така да премахнем скобите
+elements.map(element => element.length); // [8, 6, 7, 9]
+
+// In this case, because we only need the length property, we can use destructing parameter:
+// Notice that the string `"length"` corrosponds to the property we want to get whereas the
+//  obviously non-special `lengthFooBArX` is just the name of a variable which can be changed
+//  to any valid variable name you want
+elements.map(({ "length": lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
+
+// This destructing parameter assignment can be written as seen below. However, note that there
+//   is no specific `"length"` to select which property we want to get. Instead, the literal name
+//   itself of the variable `length` is used as the property we want to retrieve from the object.
+elements.map(({ length }) => length); // [8, 6, 7, 9]
+
+ +

Без отделна ключова дума this

+ +

Допреди функциите със стрелка, всяка нова функция дефинираше своя собствена стойност this  (въз основа на това как се нарича функцията, нов обект в случай на конструктор, недифинарна при извикване на функции в строг режим,основният обект ако функцията се извиква като "object method", etc.). Това се оказа по-малко от идеалното с обектно-ориентирания стил на програмиране.

+ +
function Person() {
+  // The Person() constructor defines `this` as an instance of itself.
+  this.age = 0;
+
+  setInterval(function growUp() {
+    // In non-strict mode, the growUp() function defines `this`
+    // as the global object (because it's where growUp() is executed.),
+    // which is different from the `this`
+    // defined by the Person() constructor.
+    this.age++;
+  }, 1000);
+}
+
+var p = new Person();
+ +

В ECMAScript 3/5, проблемът с  this беше поправим като присвоим стойността на  this към променлива , която може да бъде затворена.

+ +
function Person() {
+  var that = this;
+  that.age = 0;
+
+  setInterval(function growUp() {
+    // The callback refers to the `that` variable of which
+    // the value is the expected object.
+    that.age++;
+  }, 1000);
+}
+ +

Като алтернатива, може да бъде създадена свързана функция  така че  this стойността може да бъде предадена на свързаната целева функция (функцията growUp() в примера по-горе).

+ +

Функцията със стрелка няма свой собствен this; Стойността  this от използвания лексикален контекст и др. Функциите със стрелки следват нормалните правила на промелнива. Така че, докато търсим за  this,  който не присъства в текущият обхват на функцията, те взимат this от околният обхват. По този начин,в следния код,  this в рамките на функцията, която се предава на setInterval функцията, има същата стойност като на тази в околната лексикална функция:

+ +
function Person(){
+  this.age = 0;
+
+  setInterval(() => {
+    this.age++; // |this| properly refers to the Person object
+  }, 1000);
+}
+
+var p = new Person();
+ +

Връзка със строг режим

+ +

Като се има в предвид , че this идва от околния лексикален контекст, строгите правила за режима по отношение на this се игнорират.

+ +
var f = () => { 'use strict'; return this; };
+f() === window; // or the global object
+ +

Всички други правила за строг режим се прилагат нормално

+ +

Извикване чрез повикване или прилагане

+ +

Тъй като функциите със стрелка нямат свой собствен this, методите call() или apply() могат само да предават параметри. thisArg се игнорира.

+ +
var adder = {
+  base: 1,
+
+  add: function(a) {
+    var f = v => v + this.base;
+    return f(a);
+  },
+
+  addThruCall: function(a) {
+    var f = v => v + this.base;
+    var b = {
+      base: 2
+    };
+
+    return f.call(b, a);
+  }
+};
+
+console.log(adder.add(1));         // This would log to 2
+console.log(adder.addThruCall(1)); // This would log to 2 still
+ +

Без обвързване на arguments

+ +

Функциите със стрелка нямат свой собствен обект от аргументи .Следователно в този пример аргументите са просто препратка към аргументите на заобикалящото ги поле:

+ +
var arguments = [1, 2, 3];
+var arr = () => arguments[0];
+
+arr(); // 1
+
+function foo(n) {
+  var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
+  return f();
+}
+
+foo(3); // 6
+ +

В повечето случаи, използването на rest parameters(остатъчни параметри) е добра алтернатива от използването на обект с  аргументи.

+ +
function foo(n) {
+  var f = (...args) => args[0] + n;
+  return f(10);
+}
+
+foo(1); // 11
+ +

Функции със стрелка използвани като методи

+ +

Както бе посочено по-горе, изразите на функциите със стрелките са най-подходящи за функциите, различни от метода. Нека видим какво се случва, когато се опитаме да ги използваме като методи:

+ +
'use strict';
+
+var obj = {
+  i: 10,
+  b: () => console.log(this.i, this),
+  c: function() {
+    console.log(this.i, this);
+  }
+}
+
+obj.b(); // prints undefined, Window {...} (or the global object)
+obj.c(); // prints 10, Object {...}
+ +

Функциите със стрелка нямат свой собствен this. Друг пример затова е : {{jsxref("Object.defineProperty()")}}:

+ +
'use strict';
+
+var obj = {
+  a: 10
+};
+
+Object.defineProperty(obj, 'b', {
+  get: () => {
+    console.log(this.a, typeof this.a, this); // undefined 'undefined' Window {...} (or the global object)
+    return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
+  }
+});
+
+ +

Използване на оператора new

+ +

Функциите със стрелка не мога да бъдат използвани като конструктории ще генерират грешка , когато се изпозват с оператора new.

+ +
var Foo = () => {};
+var foo = new Foo(); // TypeError: Foo is not a constructor
+ +

Използване на свойството prototype

+ +

Функциите със стрелки нямат свойството prototype.

+ +
var Foo = () => {};
+console.log(Foo.prototype); // undefined
+
+ +

Използване на ключовата дума  yield

+ +

Ключовата дума yield не може да бъде използвана в тялото на функцията със стрелка ( освен когато е позволено в рамките на функциите, които са вложени в нея ). В резултат на това функциите със стрелки не могат да се използват като генератори.

+ +

Тялото на функция

+ +

Функциите със стрелка могат да имат или  "сбито тяло" или обичайното "блоково тяло".

+ +

В сбитото тяло е посочен само израз, който се превръща в неявна връщана стойност.  В блоково тяло трябва да използвате изрично return декларация за връщане.

+ +
var func = x => x * x;
+// concise body syntax, implied "return"
+
+var func = (x, y) => { return x + y; };
+// with block body, explicit "return" needed
+
+ +

Връщане на литерали на обекти

+ +

Имайте в предвид , че връщането на литерали на обекти, използвайки сбит синтаксис params => {object:literal} няма да работи според очакванията.

+ +
var func = () => { foo: 1 };
+// Calling func() returns undefined!
+
+var func = () => { foo: function() {} };
+// SyntaxError: function statement requires a name
+ +

Това е защото кодът вътре в скобите ({}) се анализита като оследователност  от изрази (или  fooсе третира като етикет, а не като ключ в буквален обект).

+ +

Запомнете, че трябва да поставяте буквалният обект в скоби , както е показано в примера по-долу.

+ +
var func = () => ({foo: 1});
+ +

Прекъсване на линията

+ +

Функцията със стрелка не може да съдържа прекъсната линия между нейните параметри и стрелка.

+ +
var func = (a, b, c)
+           => 1;
+// SyntaxError: expected expression, got '=>'
+ +

Все пак това може да бъде променено, чрез използване на скоби или поставяне на разделителната линия в аргументите, както е показано в примера по-долу, за да се гарантира, че кодът остава красив и пухкав.

+ +
var func = (
+  a,
+  b,
+  c
+) => (
+  1
+);
+// no SyntaxError thrown
+ + + +

Parsing order

+ +

Въпреки че, стрелката във функцията със стрелка не е оператор, функциите със стрелка имат специални правила, които взаимодействат по различен начин с  оператора за предимство  сравнено с нормалните функции.

+ +
let callback;
+
+callback = callback || function() {}; // ok
+
+callback = callback || () => {};
+// SyntaxError: invalid arrow-function arguments
+
+callback = callback || (() => {});    // ok
+
+ +

Още примери

+ +
// An empty arrow function returns undefined
+let empty = () => {};
+
+(() => 'foobar')();
+// Returns "foobar"
+// (this is an Immediately Invoked Function Expression
+// see 'IIFE' in glossary)
+
+var simple = a => a > 15 ? 15 : a;
+simple(16); // 15
+simple(10); // 10
+
+let max = (a, b) => a > b ? a : b;
+
+// Easy array filtering, mapping, ...
+
+var arr = [5, 6, 13, 0, 1, 18, 23];
+
+var sum = arr.reduce((a, b) => a + b);
+// 66
+
+var even = arr.filter(v => v % 2 == 0);
+// [6, 0, 18]
+
+var double = arr.map(v => v * 2);
+// [10, 12, 26, 0, 2, 36, 46]
+
+// More concise promise chains
+promise.then(a => {
+  // ...
+}).then(b => {
+  // ...
+});
+
+// Parameterless arrow functions that are visually easier to parse
+setTimeout( () => {
+  console.log('I happen sooner');
+  setTimeout( () => {
+    // deeper code
+    console.log('I happen later');
+  }, 1);
+}, 1);
+
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + +
СпецификацииСтатусКоментар
{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}}
+ +

Съвместимост с браузера

+ +
+ + +

{{Compat("javascript.functions.arrow_functions")}}

+
+ +

Вижте още

+ + diff --git a/files/bg/web/javascript/reference/functions/index.html b/files/bg/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..adb0d13f05 --- /dev/null +++ b/files/bg/web/javascript/reference/functions/index.html @@ -0,0 +1,596 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +
{{jsSidebar("Functions")}}
+ +

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

+ +

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

+ +

For more examples and explanations, see also the JavaScript guide about functions.

+ +

Description

+ +

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

+ +

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

+ +

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

+ +
/* Declare the function 'myFunc' */
+function myFunc(theObject) {
+  theObject.brand = "Toyota";
+}
+
+/*
+ * Declare variable 'mycar';
+ * create and initialize a new Object;
+ * assign reference to it to 'mycar'
+ */
+var mycar = {
+  brand: "Honda",
+  model: "Accord",
+  year: 1998
+};
+
+/* Logs 'Honda' */
+console.log(mycar.brand);
+
+/* Pass object reference to the function */
+myFunc(mycar);
+
+/*
+ * Logs 'Toyota' as the value of the 'brand' property
+ * of the object, as changed to by the function.
+ */
+console.log(mycar.brand);
+
+ +

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

+ +

Defining functions

+ +

There are several ways to define functions:

+ +

The function declaration (function statement)

+ +

There is a special syntax for declaring functions (see function statement for details):

+ +
function name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The function expression (function expression)

+ +

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

+ +
function [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
statements
+
The statements comprising the body of the function.
+
+ +

Here is an example of an anonymous function expression (the name is not used):

+ +
var myFunction = function() {
+    statements
+}
+ +

It is also possible to provide a name inside the definition in order to create a named function expression:

+ +
var myFunction = function namedFunction(){
+    statements
+}
+
+ +

One of the benefits of creating a named function expression is that in case we encountered an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

+ +

As we can see, both examples do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

+ +

When functions are used only once, a common pattern is an IIFE (Immediately Invokable Function Expression).

+ +
(function() {
+    statements
+})();
+ +

IIFE are function expressions that are invoked as soon as the function is declared.

+ +

The generator function declaration (function* statement)

+ +

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
+ +
+
statements
+
The statements comprising the body of the function.
+
+ +

The generator function expression (function* expression)

+ +

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

+ +
function* [name]([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
+
+ +
+
param
+
The name of an argument to be passed to the function.
+
statements
+
The statements comprising the body of the function.
+
+ +

The arrow function expression (=>)

+ +

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

+ +
([param[, param]]) => {
+   statements
+}
+
+param => expression
+
+ +
+
param
+
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
+
statements or expression
+
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
+
+ +

The Function constructor

+ +
+

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

+ +
new Function (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function body.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

The GeneratorFunction constructor

+ +
+

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

+
+ +
+

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

+
+ +

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

+ +
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
+
+ +
+
arg1, arg2, ... argN
+
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
+ +
+
functionBody
+
A string containing the JavaScript statements comprising the function definition.
+
+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function parameters

+ +

Default parameters

+ +

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

+ +

Rest parameters

+ +

The rest parameter syntax allows representing an indefinite number of arguments as an array. For more details, see rest parameters.

+ +

The arguments object

+ +

You can refer to a function's arguments within the function by using the arguments object. See arguments.

+ + + +

Defining method functions

+ +

Getter and setter functions

+ +

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

+ +
+
get
+
+

Binds an object property to a function that will be called when that property is looked up.

+
+
set
+
Binds an object property to a function to be called when there is an attempt to set that property.
+
+ +

Method definition syntax

+ +

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

+ +
var obj = {
+  foo() {},
+  bar() {}
+};
+ +

Constructor vs. declaration vs. expression

+ +

Compare the following:

+ +

A function defined with the Function constructor assigned to the variable multiply:

+ +
var multiply = new Function('x', 'y', 'return x * y');
+ +

A function declaration of a function named multiply:

+ +
function multiply(x, y) {
+   return x * y;
+} // there is no semicolon here
+
+ +

A function expression of an anonymous function assigned to the variable multiply:

+ +
var multiply = function(x, y) {
+   return x * y;
+};
+
+ +

A function expression of a function named func_name assigned to the variable multiply:

+ +
var multiply = function func_name(x, y) {
+   return x * y;
+};
+
+ +

Differences

+ +

All do approximately the same thing, with a few subtle differences:

+ +

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

+ +
var y = function x() {};
+alert(x); // throws an error
+
+ +

The function name also appears when the function is serialized via Function's toString method.

+ +

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope in which the function is declared.

+ +

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

+ +

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

+ +
function anonymous() {
+}
+
+ +

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

+ +
var foo = new Function("alert(anonymous);");
+foo();
+
+ +

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

+ +
foo(); // alerts FOO!
+function foo() {
+   alert('FOO!');
+}
+
+ +

A function defined by a function expression or by a function declaration inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

+ +
/*
+ * Declare and initialize a variable 'p' (global)
+ * and a function 'myFunc' (to change the scope) inside which
+ * declare a varible with same name 'p' (current) and
+ * define three functions using three different ways:-
+ *     1. function declaration
+ *     2. function expression
+ *     3. function constructor
+ * each of which will log 'p'
+ */
+var p = 5;
+function myFunc() {
+    var p = 9;
+
+    function decl() {
+        console.log(p);
+    }
+    var expr = function() {
+        console.log(p);
+    };
+    var cons = new Function('\tconsole.log(p);');
+
+    decl();
+    expr();
+    cons();
+}
+myFunc();
+
+/*
+ * Logs:-
+ * 9  - for 'decl' by function declaration (current scope)
+ * 9  - for 'expr' by function expression (current scope)
+ * 5  - for 'cons' by Function constructor (global scope)
+ */
+
+ +

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

+ +

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

+ +
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
+foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
+ +

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

+ + + +
var x = 0;               // source element
+if (x === 0) {           // source element
+   x = 10;               // not a source element
+   function boo() {}     // not a source element
+}
+function foo() {         // source element
+   var y = 20;           // source element
+   function bar() {}     // source element
+   while (y === 10) {    // source element
+      function blah() {} // not a source element
+      y++;               // not a source element
+   }
+}
+
+ +

Examples

+ +
// function declaration
+function foo() {}
+
+// function expression
+(function bar() {})
+
+// function expression
+x = function hello() {}
+
+
+if (x) {
+   // function expression
+   function world() {}
+}
+
+
+// function declaration
+function a() {
+   // function declaration
+   function b() {}
+   if (0) {
+      // function expression
+      function c() {}
+   }
+}
+
+ +

Block-level functions

+ +

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

+ +
'use strict';
+
+function f() {
+  return 1;
+}
+
+{
+  function f() {
+    return 2;
+  }
+}
+
+f() === 1; // true
+
+// f() === 2 in non-strict mode
+
+ +

Block-level functions in non-strict code

+ +

In a word: Don't.

+ +

In non-strict code, function declarations inside blocks behave strangely. For example:

+ +
if (shouldDefineZero) {
+   function zero() {     // DANGER: compatibility risk
+      console.log("This is zero.");
+   }
+}
+
+ +

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

+ +

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

+ +

A safer way to define functions conditionally is to assign a function expression to a variable:

+ +
var zero;
+if (shouldDefineZero) {
+   zero = function() {
+      console.log("This is zero.");
+   };
+}
+
+ +

Examples

+ +

Returning a formatted number

+ +

The following function returns a string containing the formatted representation of a number padded with leading zeros.

+ +
// This function returns a string padded with leading zeros
+function padZeros(num, totalLen) {
+   var numStr = num.toString();             // Initialize return value as string
+   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
+   for (var i = 1; i <= numZeros; i++) {
+      numStr = "0" + numStr;
+   }
+   return numStr;
+}
+
+ +

The following statements call the padZeros function.

+ +
var result;
+result = padZeros(42,4); // returns "0042"
+result = padZeros(42,2); // returns "42"
+result = padZeros(5,4);  // returns "0005"
+
+ +

Determining whether a function exists

+ +

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise, some other action is taken.

+ +
 if ('function' === typeof window.noFunc) {
+   // use noFunc()
+ } else {
+   // do something else
+ }
+
+ +

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.functions")}}

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/global_objects/array/index.html b/files/bg/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..1d2a114327 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,460 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - Example + - Global Objects + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

+ +

Create an Array

+ +
var fruits = ['Apple', 'Banana'];
+
+console.log(fruits.length);
+// 2
+
+ +

Access (index into) an Array item

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

Loop over an Array

+ +
fruits.forEach(function(item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

Add to the end of an Array

+ +
var newLength = fruits.push('Orange');
+// ["Apple", "Banana", "Orange"]
+
+ +

Remove from the end of an Array

+ +
var last = fruits.pop(); // remove Orange (from the end)
+// ["Apple", "Banana"];
+
+ +

Remove from the front of an Array

+ +
var first = fruits.shift(); // remove Apple from the front
+// ["Banana"];
+
+ +

Add to the front of an Array

+ +
var newLength = fruits.unshift('Strawberry') // add to the front
+// ["Strawberry", "Banana"];
+
+ +

Find the index of an item in the Array

+ +
fruits.push('Mango');
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf('Banana');
+// 1
+
+ +

Remove an item by index position

+ +
var removedItem = fruits.splice(pos, 1); // this is how to remove an item
+
+// ["Strawberry", "Mango"]
+ +

Remove items from an index position

+ +
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
+console.log(vegetables);
+// ["Cabbage", "Turnip", "Radish", "Carrot"]
+
+var pos = 1, n = 2;
+
+var removedItems = vegetables.splice(pos, n);
+// this is how to remove items, n defines the number of items to be removed,
+// from that position(pos) onward to the end of array.
+
+console.log(vegetables);
+// ["Cabbage", "Carrot"] (the original array is changed)
+
+console.log(removedItems);
+// ["Turnip", "Radish"]
+ +

Copy an Array

+ +
var shallowCopy = fruits.slice(); // this is how to make a copy
+// ["Strawberry", "Mango"]
+
+ +

Syntax

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

Parameters

+ +
+
elementN
+
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number (see the arrayLength parameter below). Note that this special case only applies to JavaScript arrays created with the Array constructor, not array literals created with the bracket syntax.
+
arrayLength
+
If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a {{jsxref("RangeError")}} exception is thrown.
+
+ +

Description

+ +

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them. In general, these are convenient characteristics; but if these features are not desirable for your particular use, you might consider using typed arrays.

+ +

Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

+ +

Accessing array elements

+ +

JavaScript arrays are zero-indexed: the first element of an array is at index 0, and the last element is at the index equal to the value of the array's {{jsxref("Array.length", "length")}} property minus 1. Using an invalid index number returns undefined.

+ +
var arr = ['this is the first element', 'this is the second element', 'this is the last element'];
+console.log(arr[0]);              // logs 'this is the first element'
+console.log(arr[1]);              // logs 'this is the second element'
+console.log(arr[arr.length - 1]); // logs 'this is the last element'
+
+ +

Array elements are object properties in the same way that toString is a property, but trying to access an element of an array as follows throws a syntax error because the property name is not valid:

+ +
console.log(arr.0); // a syntax error
+
+ +

There is nothing special about JavaScript arrays and the properties that cause this. JavaScript properties that begin with a digit cannot be referenced with dot notation; and must be accessed using bracket notation. For example, if you had an object with a property named '3d', it can only be referenced using bracket notation. E.g.:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // a syntax error
+console.log(years[0]);  // works properly
+
+ +
renderer.3d.setTexture(model, 'character.png');     // a syntax error
+renderer['3d'].setTexture(model, 'character.png');  // works properly
+
+ +

Note that in the 3d example, '3d' had to be quoted. It's possible to quote the JavaScript array indexes as well (e.g., years['2'] instead of years[2]), although it's not necessary. The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. It is, for this reason, that '2' and '02' would refer to two different slots on the years object and the following example could be true:

+ +
console.log(years['2'] != years['02']);
+
+ +

Similarly, object properties which happen to be reserved words(!) can only be accessed as string literals in bracket notation (but it can be accessed by dot notation in firefox 40.0a2 at least):

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['var']);
+
+ +

Relationship between length and numerical properties

+ +

A JavaScript array's {{jsxref("Array.length", "length")}} property and numerical properties are connected. Several of the built-in array methods (e.g., {{jsxref("Array.join", "join()")}}, {{jsxref("Array.slice", "slice()")}}, {{jsxref("Array.indexOf", "indexOf()")}}, etc.) take into account the value of an array's {{jsxref("Array.length", "length")}} property when they're called. Other methods (e.g., {{jsxref("Array.push", "push()")}}, {{jsxref("Array.splice", "splice()")}}, etc.) also result in updates to an array's {{jsxref("Array.length", "length")}} property.

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's {{jsxref("Array.length", "length")}} property accordingly:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

Increasing the {{jsxref("Array.length", "length")}}.

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +

Decreasing the {{jsxref("Array.length", "length")}} property does, however, delete elements.

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

This is explained further on the {{jsxref("Array.length")}} page.

+ +

Creating an array using the result of a match

+ +

The result of a match between a regular expression and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by {{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, and {{jsxref("String.replace")}}. To help explain these properties and elements, look at the following example and then refer to the table below:

+ +
// Match one d followed by one or more b's followed by one d
+// Remember matched b's and the following d
+// Ignore case
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

The properties and elements returned from this match are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Property/ElementDescriptionExample
inputA read-only property that reflects the original string against which the regular expression was matched.cdbBdbsbz
indexA read-only property that is the zero-based index of the match in the string.1
[0]A read-only element that specifies the last matched characters.dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

Properties

+ +
+
Array.length
+
The Array constructor's length property whose value is 1.
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Array.prototype")}}
+
Allows the addition of properties to all array objects.
+
+ +

Methods

+ +
+
{{jsxref("Array.from()")}}
+
Creates a new Array instance from an array-like or iterable object.
+
{{jsxref("Array.isArray()")}}
+
Returns true if a variable is an array, if not false.
+
{{jsxref("Array.of()")}}
+
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
+
+ +

Array instances

+ +

All Array instances inherit from {{jsxref("Array.prototype")}}. The prototype object of the Array constructor can be modified to affect all Array instances.

+ +

Properties

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

Methods

+ +

Mutator methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array generic methods

+ +
+

Array generics are non-standard, deprecated and will get removed in the near future

+
+ +

Sometimes you would like to apply array methods to strings or other array-like objects (such as function {{jsxref("Functions/arguments", "arguments", "", 1)}}). By doing this, you treat a string as an array of characters (or otherwise treat a non-array as an array). For example, in order to check that every character in the variable str is a letter, you would write:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

This notation is rather wasteful and JavaScript 1.6 introduced a generic shorthand:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} are also available on {{jsxref("String")}}.

+ +

These are not part of ECMAScript standards and they are not supported by non-Gecko browsers. As a standard alternative, you can convert your object to a proper array using {{jsxref("Array.from()")}}; although that method may not be supported in old browsers:

+ +
if (Array.from(str).every(isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

Examples

+ +

Creating an array

+ +

The following example creates an array, msgArray, with a length of 0, then assigns values to msgArray[0] and msgArray[99], changing the length of the array to 100.

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

Creating a two-dimensional array

+ +

The following creates a chess board as a two-dimensional array of strings. The first move is made by copying the 'p' in (6,4) to (4,4). The old position (6,4) is made blank.

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// Move King's Pawn forward 2
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

Here is the output:

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

Using an array to tabulate a set of values

+ +
values = [];
+for (var x = 0; x < 10; x++){
+ values.push([
+  2 ** x,
+  2 * x ** 2
+ ])
+};
+console.table(values)
+ +

Results in

+ +
0	1	0
+1	2	2
+2	4	8
+3	8	18
+4	16	32
+5	32	50
+6	64	72
+7	128	98
+8	256	128
+9	512	162
+ +

(First column is the (index))

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}New methods added: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}New methods added: {{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ES7', '#sec-array-objects', 'Array')}}{{Spec2('ES7')}}New method added: {{jsxref("Array.prototype.includes()")}}
{{SpecName('ESDraft', '#sec-array-objects', 'Array')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Array")}}

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/global_objects/array/splice/index.html b/files/bg/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..36d82dc700 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,155 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - JavaScript + - splice + - Масив + - заместване + - метод + - премахване +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

Методът splice() променя съдържанието на масива като изтрива или заменя съществуващи елементи и/или добавя нови.

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ + + +

Синтаксис

+ +
let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

Параметри

+ +
+
start
+
Индексът, от който започва промяната на масива.
+
Ако числото е по-голямо от дължината на масива, стойността на start ще се промени автоматично и ще приеме стойност равна на дължината на масива. В този случай няма да бъдат изтрити елементи от масива. Методът ще се държи като функция за добавяне на елементи и ще добави толкова елементи колкото са подадени като item[n*].
+
Ако start е отрицателно число обработката на масива ще започне от края на масива.( Случай че, start e -1 това означава -n е индексът на n-тия последен елемент и следователно е еквивалентен на array.length - n ).
+
Ако array.length + start е по-малко от 0, ще започне от индекс 0.
+
deleteCount {{optional_inline}}
+
Число, което показва колко елемента трябва да бъдат изтрити ( започва се от start ).
+
If deleteCount is omitted, or if its value is equal to or larger than array.length - start (that is, if it is equal to or greater than the number of elements left in the array, starting at start), then all the elements from start to the end of the array will be deleted.
+
+
+

Note: In IE8, it won't delete all when deleteCount is omitted.

+
+
+
If deleteCount is 0 or negative, no elements are removed. In this case, you should specify at least one new element (see below).
+
item1, item2, ... {{optional_inline}}
+
The elements to add to the array, beginning from start. If you do not specify any elements, splice() will only remove elements from the array.
+
+ +

Върната стойност

+ +

Методът връща масив, съдържащ изтритите елементи.

+ +

Ако само един елемент е премахнат, резултатът ще бъде масив с един елемент.

+ +

Ако няма изтрити елементи, резултатът ще бъде празен масив.

+ +

Описание

+ +

Ако броя на добавените елементи се различава от броя на изтритите, ще има промяна в дължината на масива.

+ +

Примери

+ +

Премахват се 0 елемента пред индекс 2 и се добавя "drum"

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+// Ако изходният ви код е в utf8, можете да ползвате всякакви азбуки
+let премахнат = myFish.splice(2, 0, 'drum')
+
+// myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// премахнат = [], не са премахнати елементи
+ +

Премахват се 0 елемента пред индекс 2 и се добавят "drum" и "guitar"

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(2, 0, 'drum', 'guitar')
+
+// myFish = ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
+// removed = [], не са премахнати елементи
+
+ +

Премахва се един елемент, започвайки от индекс 3

+ +
let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
+let removed = myFish.splice(3, 1)
+
+// removed = ["mandarin"]
+// myFish = ["angel", "clown", "drum", "sturgeon"]
+
+ +

Remove 1 element at index 2, and insert "trumpet"

+ +
let myFish = ['angel', 'clown', 'drum', 'sturgeon']
+let removed = myFish.splice(2, 1, 'trumpet')
+
+// myFish = ["angel", "clown", "trumpet", "sturgeon"]
+// removed = ["drum"]
+ +

Remove 2 elements from index 0, and insert "parrot", "anemone" and "blue"

+ +
let myFish = ['angel', 'clown', 'trumpet', 'sturgeon']
+let removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue')
+
+// myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
+// removed = ["angel", "clown"]
+ +

Remove 2 elements from index 2

+ +
let myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon']
+let removed = myFish.splice(2, 2)
+
+// myFish = ["parrot", "anemone", "sturgeon"]
+// removed = ["blue", "trumpet"]
+ +

Remove 1 element from index -2

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(-2, 1)
+
+// myFish = ["angel", "clown", "sturgeon"]
+// removed = ["mandarin"]
+ +

Remove all elements after index 2 (incl.)

+ +
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
+let removed = myFish.splice(2)
+
+// myFish = ["angel", "clown"]
+// removed = ["mandarin", "sturgeon"]
+ +

Спецификация

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}
+ +

Съвместимост и подръжка

+ +
+ + +

{{Compat("javascript.builtins.Array.splice")}}

+
+ +

Виж повече

+ + diff --git a/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html b/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..6849a4d7b2 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,96 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +
{{JSRef}}
+ +
+ +

ArrayBuffer обекта се използва за репрезентиране на най общ бъфер за двоични данни със статична дължина.

+ +

Това е масив от байтове, често наричан в други езици "byte array".Не можете директно да манипулирате съдържанието на ArrayBuffer; вместо това вие трябва да създадете масив от типизирани обекти или {{jsxref("DataView")}} обект, който ще представлява бъфера в специфичен формат, който ще се използва за да чете съдържанието на бъфера.

+ +

ArrayBuffer() конструктора създава нов ArrayBuffer от подадена дължина в байтове, можете също да получите ArrayBuffer от вече съществуващи данни, например от Base64 низ или от файл от вашата система.

+ +

Конструктор

+ +
+
{{jsxref("ArrayBuffer.ArrayBuffer", "ArrayBuffer()")}}
+
Създава нови ArrayBuffer обекти.
+
+ +

Свойства

+ +
+
ArrayBuffer.length 
+
Връща броя параметри на конструктор функцията на ArrayBuffer , който е 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
Конструктор функцията, която се използва за създаване на нови обекти.
+
ArrayBuffer.prototype
+
Позволява за добавянето на допълнителни свойства към всички ArrayBuffer обекти.
+
+ +

Методи

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Връща true ако arg е един от буферните масивни типове, като масив от типизирани обекти или {{jsxref("DataView")}}. Връща false в противен случай.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}}
+
+
Връща нов ArrayBuffer ,чието съдържание е взето от данните на oldBuffer и след това се скъсява или се доплъват водещите нули (zero-extended) с newByteLength.
+
+
+ +

Инстанции

+ +

Всички ArrayBuffer инстанции наследяват ArrayBuffer.prototype.

+ +

Свойства

+ +
+
ArrayBuffer.prototype.constructor
+
Е функцията, която създава прототипа на обекта. Началната стойност е стандартният, вграден конструктор на ArrayBuffer.
+
{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
+
Големината, в байтове на ArrayBuffer. Това се установява когато масива се създава и не може да се променя.
+
+ +

Методи

+ +
+
{{jsxref("ArrayBuffer.prototype.slice()")}}
+
Връща нов ArrayBuffer, чието съдържание е копие на байтовете на този ArrayBuffer от begin(началото), включително, до end(края), изключае.Ако някое от begin или end е отрицателно, се отнася към индекс в края на масива, вместо в началото.
+
+ +

Пример

+ +

В този пример ще създадем 8-битов бъфер с {{jsxref("Int32Array")}}  изглед, рефериращ към бъфера:

+ +
const buffer = new ArrayBuffer(8);
+const view = new Int32Array(buffer);
+ +

Спецификации

+ + + + + + + + + + +
Спецификация
{{SpecName('ESDraft', '#sec-arraybuffer-objects', 'ArrayBuffer')}}
+ +

Съвместимост на браузъра

+ + + +

{{Compat("javascript.builtins.ArrayBuffer")}}

+ +

Вижте също

+ + diff --git a/files/bg/web/javascript/reference/global_objects/index.html b/files/bg/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..6af3563dd3 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/index.html @@ -0,0 +1,182 @@ +--- +title: Standard built-in objects +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Overview + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +

{{JSSidebar("Objects")}}

+ +

This chapter documents all of JavaScript's standard, built-in objects, including their methods and properties.

+ +

The term "global objects" (or standard built-in objects) here is not to be confused with the global object. Here, global objects refer to objects in the global scope. The global object itself can be accessed using the {{JSxRef("Operators/this", "this")}} operator in the global scope (but only if ECMAScript 5 strict mode is not used; in that case it returns {{JSxRef("undefined")}}). In fact, the global scope consists of the properties of the global object, including inherited properties, if any.

+ +

Other objects in the global scope are either created by the user script or provided by the host application. The host objects available in browser contexts are documented in the API reference. For more information about the distinction between the DOM and core JavaScript, see JavaScript technologies overview.

+ +

Standard objects by category

+ +

Value properties

+ +

These global properties return a simple value; they have no properties or methods.

+ + + +

Function properties

+ +

These global functions—functions which are called globally rather than on an object—directly return their results to the caller.

+ + + +

Fundamental objects

+ +

These are the fundamental, basic objects upon which all other objects are based. This includes objects that represent general objects, functions, and errors.

+ + + +

Numbers and dates

+ +

These are the base objects representing numbers, dates, and mathematical calculations.

+ + + +

Text processing

+ +

These objects represent strings and support manipulating them.

+ + + +

Indexed collections

+ +

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

+ + + +

Keyed collections

+ +

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

+ + + +

Structured data

+ +

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

+ + + +

Control abstraction objects

+ + + +

Reflection

+ + + +

Internationalization

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

WebAssembly

+ + + +

Other

+ + diff --git a/files/bg/web/javascript/reference/global_objects/promise/index.html b/files/bg/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..3145756561 --- /dev/null +++ b/files/bg/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,253 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +tags: + - JavaScript + - Promises + - Refere +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Promise обектът представлява евентуалният завършек (или неуспех) на една асинхронна операция и нейната получена стойност.

+ +
+

Бележка:  Тази статия описва Promise конструктора и методите и свойствата на такива обекти. За да научите начина по който работят promisesи как може да ги използвате , съветваме ви първо да прочетете Как да използваме promises.  Конструктора се използва предимно за обхващане на функции, които вече не поддържат promises

+
+ +
{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}
+ + + +

Синтаксис

+ +
new Promise(executor);
+ +

Параметри

+ +
+
екзекутор (executor)
+
Функция , която се предава с аргументи resolve и reject. Екзекутор (executor) функцията се изпълнява незабавно след  изпълнението на Promise, предава resolve и reject функции (Екзекутора (executor) се извиква преди Promise конструктора , дори връща създадения обект). resolve и reject функциите, когато се извикват, разрешават или отхвърлят съответния  promise. Екзекутора (executor) обикновено инициира някаква асинхронна работа и след като веднъж приключи, извиква resolve функцията, за да разреши promise или дори да го отхвъли ако възникне грешка. Ако възникне грешка в екзекутора (executor) , promise  се отхвърля и върнатата стойност от екзекутора (executor) се отхвърля.
+
+ +

Описание

+ +

Promise е прокси за стойността, която не е непременно известна , когато се създава promise. Позволява ви да свържете манипулаторите с асинхронно действие, евентуално връщайки успешна стойност или грешка. Това позволява асинхронните методи да връщат стойност като синхронни методи: вместо да ни върне незабавно финална стойност, асинхронния метод връща promise, който да ни предостави стойността в някакъв бъдещ момент.

+ +

Promise се намира в едно от тези състояния:

+ + + +

Изчакващият promise може да бъде изпълнен със стойност или отказан с описание за грешка. Когато някоя от тези опции се случи, се извикват асоциираните манипулатори, поставени на опашка, след което се извикват then методите. (Ако promise вече е бил изпълнен или отказан, когато е приложен съответния манипулатор , манипулатора ще бъде извикан. Така че няма никакво състезателно условие между завършването на асинхронната операция и манипулаторите които са и били приложени.)

+ +

Като {{jsxref("Promise.then", "Promise.prototype.then()")}} и {{jsxref("Promise.catch", "Promise.prototype.catch()")}} методи връщат promises, те могат да бъдат обхванати.

+ +

+ +
+

Забележка, не трябва да се бърка с:  Няколко дргуи езика имат механизъм за мързеливо (lazy) оценяване и отлагане на изчисления, които те също наричат "promises" ... схема. Promises в JavaScript представляват процеси, които вече се случват и могат да бъдат обхванати с функции за обратно извикване (callback functions).  Ако търсите мързеливо да изчислите израз, разгледайте функциите със стрелка (arrow function) без аргументи: f = () => израз(expression) за създаване на мързеливо-изчислителен израз  и f() за изчисление.

+
+ +
+

Забележка: Казва се че Promise се счита за установен ако е изпълнен или отказан, но не изчакващ. Също така ще чуете и термина resolved, който се изпозлва с promises — това означава че promise е установен или “заключен”, изчаквайки да съответства на състоянието на друг promise. States and fates съдържа повече детайли относно promise терминологията.

+
+ +

Свойства

+ +
+
Promise.length
+
Дължина на свойство, чиято дължина е винаги 1 (номер на аругмента на конструктора).
+
{{jsxref("Promise.prototype")}}
+
Представялва прототипа на Promise конструктора.
+
+ +

Методи

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
Изчаква всички promises да бъдат разрешени или отказани.
+
Ако върнатия promise е решен(resolves), той се решава с агрегиращ масив от стойности от разрешените promises в същата последователност, както е дефиниран в многобройните promises. Ако е отхвърлен, той се отхвърля с причина от първият promise който е бил отказан.
+
{{jsxref("Promise.allSettled", "Promise.allSettled()")}}
+
Изчаква докато всички promises са приключени/уредени (всеки може да бъде разрешен или отказан).
+
Връща promise което се решава след всички дадени promises били те разрешени или отказани, с масив от обекти , които описват резултата от всеки promise.
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
Изчаква докато някой от promises е разрешен или отказан.
+
Ако върнатият promise е разрешен,е разрешен със стойноста от първият promise.Ако е отказан, е отакзан с причината от първият promise който е бил отказан.
+
{{jsxref("Promise.reject", "Promise.reject()")}}
+
Връща нов Promise обект, който е отказан с предоставена причина.
+
{{jsxref("Promise.resolve", "Promise.resolve()")}}
+
Връща нов Promise който е разрешен с дадената му стойност. Ако стойността е  thenable (i.e. има then метод), върнатият promise ще "следва" този thenable, приемайки евентуалното му състояние; в противен случай върнатия promise ще бъде запълнен със стойността. Обикновенно ако не знаете дадена стойност дали е promise или не, {{jsxref("Promise.resolve", "Promise.resolve(value)")}} замества и работи с върнатата стойност като promise.
+
+ +

Promise прототип

+ +

Свойства

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Properties')}}

+ +

Методи

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Promise/prototype','Methods')}}

+ +

Създаване на Promise

+ +

Promise се създава, използвайки ключовата дума new и нейният конструктор. Този конструктор приема като аргумент функция, наричаща се "executor function". Тази функция трябва да приеме две функции като параметри. Първата от тези функции (resolve) се извиква когато асинхронната задача завърши успешно и върне резултата от задачата като стойност. Вторият (reject) се извиква когато задачата се провали и връща причината за този провал, който обикновенно е обект съдържайки в себе си грешката.

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // do something asynchronous which eventually calls either:
+  //
+  //   resolve(someValue); // fulfilled
+  // or
+  //   reject("failure reason"); // rejected
+});
+
+ +

За да предоставите функция с promise функционалност, просто върнете promise:

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest();
+    xhr.open("GET", url);
+    xhr.onload = () => resolve(xhr.responseText);
+    xhr.onerror = () => reject(xhr.statusText);
+    xhr.send();
+  });
+}
+ +

Примери

+ +

Основни примери

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // We call resolve(...) when what we were doing asynchronously was successful, and reject(...) when it failed.
+  // In this example, we use setTimeout(...) to simulate async code.
+  // In reality, you will probably be using something like XHR or an HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // Yay! Everything went well!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage is whatever we passed in the resolve(...) function above.
+  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
+  console.log("Yay! " + successMessage);
+});
+
+ +

Разширени примери

+ + + +

Този малък пример показва механизма на Promise. testPromise() метод се извиква всеки път когато  {{HTMLElement("button")}} е натиснат. Създава promise който ще бъде изпълнен, използвайки {{domxref("window.setTimeout()")}}, към promise броенето(номер започващ от 1) на всеки 1-3 секунди на случаен принцип. The Promise() се използва за създаването на promise.

+ +

Изпълнението на promise е просто записано, чрез сет за обратно извикване (callback set) , използвайки {{jsxref("Promise.prototype.then()","p1.then()")}}. Няколко logs (данни) показват как синхронната част на метода е отделена от асинхронното завършване на обещанието.

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    let thisPromiseCount = ++promiseCount;
+
+    let log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // We make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
+    let p1 = new Promise(
+        // The executor function is called with the ability to resolve or
+        // reject the promise
+       (resolve, reject) => {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // This is only an example to create asynchronism
+            window.setTimeout(
+                function() {
+                    // We fulfill the promise !
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // We define what to do when the promise is resolved with the then() call,
+    // and what to do when the promise is rejected with the catch() call
+    p1.then(
+        // Log the fulfillment value
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
+        }).catch(
+        // Log the rejection reason
+       (reason) => {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+ + + +

Този пример ще се стартира като кликнете на бутона. Имате нужда от браузер който поддържа Promise. Натискайки на бутона няколко пъти в кратки периоди от време , ще видите дори разллични promises , които се изпълняват един след друг.

+ +

{{EmbedLiveSample("Advanced_Example", "500", "200")}}

+ +

Зареждане на снимка с XHR

+ +

Друг опростен пример използва Promise и {{domxref("XMLHttpRequest")}} за зареждане на снимки е наличен в GitHub профила на MDN и се казва js-examples. Тук също може да го видите и в действие see it in action. Всяка стъпка е коментирана и ви позволява да следвате Promise и XHR архитектурата внимателно.

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}}
+ +

Съвместимост с браузърите

+ + + +

{{Compat("javascript.builtins.Promise")}}

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/index.html b/files/bg/web/javascript/reference/index.html new file mode 100644 index 0000000000..fedbcb5e2d --- /dev/null +++ b/files/bg/web/javascript/reference/index.html @@ -0,0 +1,51 @@ +--- +title: Справочник за JavaScript +slug: Web/JavaScript/Reference +tags: + - JavaScript + - NeedsTranslation + - TopicStub + - 'l10n:priority' +translation_of: Web/JavaScript/Reference +--- +
{{JsSidebar}}
+ +

Тази част от раздела JavaScript в MDN служи като хранилище за сведения за езика за програмиране JavaScript. Прочетете повече за този справочник.

+ +

Глобални обекти

+ +

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard_objects_by_category')}}
+ +

Statements

+ +

This chapter documents all the JavaScript statements and declarations.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
+ +

Изрази и оператори

+ +

This chapter documents all the JavaScript expressions and operators.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
+ +

Functions

+ +

This chapter documents how to work with JavaScript functions to develop your applications.

+ + + +

Additional reference pages

+ + diff --git a/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html b/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html new file mode 100644 index 0000000000..83f26e031d --- /dev/null +++ b/files/bg/web/javascript/reference/operators/arithmetic_operators/index.html @@ -0,0 +1,293 @@ +--- +title: Arithmetic operators +slug: Web/JavaScript/Reference/Operators/Arithmetic_Operators +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

Аритметичните оператори приемат числови стойности като техен операнд и връща единична числова стойност. Стандартните аритметични оператори са събиране (+), изваждане (-), умножение (*), делене(/)

+ +
{{EmbedInteractiveExample("pages/js/expressions-arithmetic.html")}}
+ + + +

Събиране (+)

+ +

Операторът за събиране произвежда сумата от числови операнди или конкатенация на стрингове.

+ +

Синтаксис

+ +
Operator: x + y
+
+ +

Примери

+ +
// Number + Number -> събиране
+1 + 2 // 3
+
+// Boolean + Number -> събиране
+true + 1 // 2
+
+// Boolean + Boolean -> събиране
+false + false // 0
+
+// Number + String -> конкатенация
+5 + 'foo' // "5foo"
+
+// String + Boolean -> конкатенация
+'foo' + false // "foofalse"
+
+// String + String -> конкатенация
+'foo' + 'bar' // "foobar"
+
+ +

Subtraction (-)

+ +

The subtraction operator subtracts the two operands, producing their difference.

+ +

Syntax

+ +
Operator: x - y
+
+ +

Examples

+ +
5 - 3     // 2
+3 - 5     // -2
+'foo' - 3 // NaN
+ +

Division (/)

+ +

The division operator produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

+ +

Syntax

+ +
Operator: x / y
+
+ +

Examples

+ +
1 / 2      // returns 0.5 in JavaScript (In Java, returns 0; both are integers)
+// (neither 1 nor 2 is explicitly a floating point number)
+
+Math.floor(3 / 2) // returns 1
+1.0 / 2.0  // returns 0.5 in both JavaScript and Java
+
+2.0 / 0    // returns Infinity
+2.0 / 0.0  // ditto, because 0.0 === 0
+2.0 / -0.0 // returns -Infinity
+ +

Multiplication (*)

+ +

The multiplication operator produces the product of the operands.

+ +

Syntax

+ +
Operator: x * y
+
+ +

Examples

+ +
 2 * 2 // 4
+-2 * 2 // -4
+Infinity * 0 // NaN
+Infinity * Infinity // Infinity
+'foo' * 2 // NaN
+
+ +

Remainder (%)

+ +

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

+ +

Syntax

+ +
Operator: var1 % var2
+
+ +

Examples

+ +
 12 % 5 //  2
+-12 % 5 // -2
+-1 % 2  // -1
+ 1 % -2 //  1
+NaN % 2 // NaN
+ 1 % 2  //  1
+ 2 % 3  //  2
+-4 % 2  // -0
+5.5 % 2 // 1.5
+
+ +

Exponentiation (**)

+ +

The exponentiation operator returns the result of raising the first operand to the power of the second operand. That is, var1var2, in the preceding statement, where var1 and var2 are variables. The exponentiation operator is right-associative. a ** b ** c is equal to a ** (b ** c).

+ +

Syntax

+ +
Operator: var1 ** var2
+
+ +

Notes

+ +

In most languages, such as PHP, Python, and others that have an exponentiation operator (**), the exponentiation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. For example, in Bash, the ** operator is defined to have a lower precedence than unary operators.

+ +

In JavaScript, it is impossible to write an ambiguous exponentiation expression; that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number.

+ +
-2 ** 2;
+// 4 in Bash, -4 in other languages.
+// This is invalid in JavaScript, as the operation is ambiguous.
+
+
+-(2 ** 2);
+// -4 in JavaScript and the author's intention is unambiguous.
+
+ +

Examples

+ +
2 ** 3 // 8
+3 ** 2 // 9
+3 ** 2.5 // 15.588457268119896
+10 ** -1 // 0.1
+NaN ** 2 // NaN
+
+2 ** 3 ** 2 // 512
+2 ** (3 ** 2) // 512
+(2 ** 3) ** 2 // 64
+
+ +

To invert the sign of the result of an exponentiation expression:

+ +
-(2 ** 2) // -4
+
+ +

To force the base of an exponentiation expression to be a negative number:

+ +
(-2) ** 2 // 4
+
+ +
+

Note: JavaScript also has a bitwise operator ^ (logical XOR). ** and ^ are different (for example : 2 ** 3 === 8 when 2 ^ 3 === 1.)

+
+ +

Increment (++)

+ +

The increment operator increments (adds one to) its operand and returns a value.

+ + + +

Syntax

+ +
Operator: x++ or ++x
+
+ +

Examples

+ +
// Postfix
+var x = 3;
+y = x++; // y = 3, x = 4
+
+// Prefix
+var a = 2;
+b = ++a; // a = 3, b = 3
+
+ +

Decrement (--)

+ +

The decrement operator decrements (subtracts one from) its operand and returns a value.

+ + + +

Syntax

+ +
Operator: x-- or --x
+
+ +

Examples

+ +
// Postfix
+var x = 3;
+y = x--; // y = 3, x = 2
+
+// Prefix
+var a = 2;
+b = --a; // a = 1, b = 1
+
+ +

Unary negation (-)

+ +

The unary negation operator precedes its operand and negates it.

+ +

Syntax

+ +
Operator: -x
+
+ +

Examples

+ +
var x = 3;
+y = -x; // y = -3, x = 3
+
+// Unary negation operator can convert non-numbers into a number
+var x = "4";
+y = -x; // y = -4
+
+ +

Unary plus (+)

+ +

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal (0x-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to {{jsxref("NaN")}}.

+ +

Syntax

+ +
Operator: +x
+
+ +

Examples

+ +
+3     // 3
++'3'   // 3
++true  // 1
++false // 0
++null  // 0
++function(val){ return val } // NaN
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-additive-operators', 'Additive operators')}}
{{SpecName('ESDraft', '#sec-postfix-expressions', 'Postfix expressions')}}
{{SpecName('ESDraft', '#sec-11.5', 'Multiplicative operators')}}
{{SpecName('ESDraft', '#sec-11.4', 'Unary operator')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators.arithmetic")}}

+ +

See also

+ + diff --git a/files/bg/web/javascript/reference/operators/index.html b/files/bg/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..64ff89da64 --- /dev/null +++ b/files/bg/web/javascript/reference/operators/index.html @@ -0,0 +1,310 @@ +--- +title: Expressions and operators +slug: Web/JavaScript/Reference/Operators +tags: + - JavaScript + - NeedsTranslation + - Operators + - Overview + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

This chapter documents all the JavaScript language operators, expressions and keywords.

+ +

Expressions and operators by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Primary expressions

+ +

Basic keywords and general expressions in JavaScript.

+ +
+
{{jsxref("Operators/this", "this")}}
+
The this keyword refers to a special property of an execution context.
+
{{jsxref("Operators/function", "function")}}
+
The function keyword defines a function expression.
+
{{jsxref("Operators/class", "class")}}
+
The class keyword defines a class expression.
+
{{jsxref("Operators/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{jsxref("Operators/yield", "yield")}}
+
Pause and resume a generator function.
+
{{jsxref("Operators/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Operators/async_function", "async function")}}
+
The async function defines an async function expression.
+
{{jsxref("Operators/await", "await")}}
+
Pause and resume an async function and wait for the promise's resolution/rejection.
+
{{jsxref("Global_Objects/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operators/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{jsxref("Operators/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operators/new", "new")}}
+
The new operator creates an instance of a constructor.
+
new.target
+
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
+
{{jsxref("Operators/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{jsxref("Operators/Spread_syntax", "...obj")}}
+
Spread syntax allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
+
Postfix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
+
Postfix decrement operator.
+
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
+
Prefix increment operator.
+
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

+ +
+
{{jsxref("Operators/delete", "delete")}}
+
The delete operator deletes a property from an object.
+
{{jsxref("Operators/void", "void")}}
+
The void operator discards an expression's return value.
+
{{jsxref("Operators/typeof", "typeof")}}
+
The typeof operator determines the type of a given object.
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
+
The unary plus operator converts its operand to Number type.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
+
The unary negation operator converts its operand to Number type and then negates it.
+
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
+
Bitwise NOT operator.
+
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
+
Logical NOT operator.
+
+ +

Arithmetic operators

+ +

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

+ +
+
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
+
Addition operator.
+
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
+
Subtraction operator.
+
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
+
Division operator.
+
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
+
Multiplication operator.
+
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
+
Remainder operator.
+
+ +
+
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
+
Exponentiation operator.
+
+ +

Relational operators

+ +

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

+ +
+
{{jsxref("Operators/in", "in")}}
+
The in operator determines whether an object has a given property.
+
{{jsxref("Operators/instanceof", "instanceof")}}
+
The instanceof operator determines whether an object is an instance of another object.
+
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +
+

Note: => is not an operator, but the notation for Arrow functions.

+
+ +

Equality operators

+ +

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

+ +
+
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
+
Equality operator.
+
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
+
Inequality operator.
+
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
+
Identity operator.
+
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
+
Nonidentity operator.
+
+ +

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
+
Bitwise left shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
+
Bitwise right shift operator.
+
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
+
Bitwise unsigned right shift operator.
+
+ +

Binary bitwise operators

+ +

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

+ +
+
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
+
Bitwise AND.
+
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
+
Bitwise OR.
+
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
+
Bitwise XOR.
+
+ +

Binary logical operators

+ +

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

+ +
+
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
+
Logical AND.
+
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
+
Logical OR.
+
+ +

Conditional (ternary) operator

+ +
+
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
+
+

The conditional operator returns one of two values based on the logical value of the condition.

+
+
+ +

Assignment operators

+ +

An assignment operator assigns a value to its left operand based on the value of its right operand.

+ +
+
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
+
Assignment operator.
+
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
+
Multiplication assignment.
+
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
+
Division assignment.
+
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
+
Remainder assignment.
+
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
+
Addition assignment.
+
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
+
Subtraction assignment
+
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
+
Left shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
+
Right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
+
Unsigned right shift assignment.
+
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
+
Bitwise AND assignment.
+
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
+
Bitwise XOR assignment.
+
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
+
Bitwise OR assignment.
+
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
+ {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
+
+

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

+
+
+ +

Comma operator

+ +
+
{{jsxref("Operators/Comma_Operator", ",")}}
+
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
+
+ +

Non-standard features {{non-standard_inline}}

+ +
+
{{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}} {{non-standard_inline}}{{obsolete_inline(60)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
{{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
Array comprehensions.
+
{{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}} {{non-standard_inline}}{{obsolete_inline(58)}}
+
Generator comprehensions.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread syntax, rest syntax, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.operators")}}

+ +

See also

+ + diff --git "a/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" "b/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" new file mode 100644 index 0000000000..e8a9b0dfe1 --- /dev/null +++ "b/files/bg/web/javascript/reference/operators/\321\200\320\260\320\267\320\277\321\200\320\265\320\264\320\265\320\273\321\217\321\211_\321\201\320\270\320\275\321\202\320\260\320\272\321\201\320\270\321\201/index.html" @@ -0,0 +1,248 @@ +--- +title: Разпределящ синтаксис +slug: Web/JavaScript/Reference/Operators/разпределящ_синтаксис +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +

Разпределящият синтаксис позволява на итериращ се израз като масив или символен низ да бъде разширен на места, където се използват нула или повече аргументи (или извиквания на функции), елементи (дефиниция на масиви), както и обект да бъде разширен на места, където се очакват нула или повече двойки от тип ключ-стойност (дефиниция на обекти).

+ +
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
+ + + +

Синтаксис

+ +

За извиквания на функции:

+ +
myFunction(...iterableObj);
+
+ +

За стойности на масиви или символни низове:

+ +
[...iterableObj, '4', 'five', 6];
+ +

За стойности на обекти (ново от ECMAScript 2018):

+ +
let objClone = { ...obj };
+ +

Примери

+ +

Разпределящ синтаксис при извикване на функции

+ +

Замяна на apply()

+ +

Често се използва {{jsxref("Function.prototype.apply()")}} в случаите, когато искаме да използваме елементите на даден масив като аргументи на функция. 

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction.apply(null, args);
+ +

С разпределящия синтаксис можем да запишем горния израз по следния начин: 

+ +
function myFunction(x, y, z) { }
+var args = [0, 1, 2];
+myFunction(...args);
+ +

Всеки аргумент в списъка от аргументи може да използва разпределящия синтаксис и той може да бъде използван няколко пъти.

+ +
function myFunction(v, w, x, y, z) { }
+var args = [0, 1];
+myFunction(-1, ...args, 2, ...[3]);
+ +

Използване на аpply вместо new за конструиране на обект

+ +

Когато извикваме конструктор с {{jsxref("Operators/new", "new")}} не е възможно директно да бъде използван масив и функцията apply(apply прави [[Извикване]], а не [[Конструиране]]). С помощта на разпределящия синтаксис обаче масивът може да бъде използван лесно за конструиране на обект:

+ +
var dateFields = [1970, 0, 1];  // 1 Jan 1970
+var d = new Date(...dateFields);
+
+ +

За да използваме new с масив от параметри без разпределящ синтаксис, трябва да го направим косвено чрез прилагане на части:

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (вътрешна бележка за myConstructor):           arguments.length: 6
+// (вътрешна бележка myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (бележка на "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

Разпределящ синтаксис при стойности на масиви

+ +

По-мощен запис при създаване на масив

+ +

Без разпределящ синтаксис създаването на нов масив с помощта на вече съществуващ като част от него, синтаксисът за създаване на масив вече не върши работа. Трябва да пишем повече, например да използваме някой от следните методи: {{jsxref("Array.prototype.push", "push()")}}, {{jsxref("Array.prototype.splice", "splice()")}}, {{jsxref("Array.prototype.concat", "concat()")}} и т.н. Използвайки разпределящия синтаксис записът става много по-кратък:

+ +
var parts = ['shoulders', 'knees'];
+var lyrics = ['head', ...parts, 'and', 'toes'];
+// ["head", "shoulders", "knees", "and", "toes"]
+
+ +

Както се използва разпределящ синтаксис за списък от аргументи, ... може да бъде използван и при създаване на масив, и то многократно.

+ +

Копиране на масив

+ +
var arr = [1, 2, 3];
+var arr2 = [...arr]; // като arr.slice()
+arr2.push(4);
+
+// arr2 става [1, 2, 3, 4]
+// arr остава неафектиран
+
+ +
+

Забележка: Разпределящият синтаксис ефективно минава едно ниво по-дълбоко докато копира масив. Затова може да не е подходящ за копиране на многомерни масиви както показва следния пример(същото е с {{jsxref("Object.assign()")}} и разпределящ синтаксис).

+
+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// Сега масивът a също е афектиран: [[], [2], [3]]
+
+ +

По-добър начин за конкатениране на масиви

+ +

{{jsxref("Array.prototype.concat()")}} често е използван за конкатениране на масив към края на вече съществуващ масив. Без използване на разпределящ синтаксис това може да бъде направено по следния начин:

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Добавя всички елементи от arr2 след тези на arr1
+arr1 = arr1.concat(arr2);
+ +

С разпределящ синтаксис това има вида: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr1, ...arr2]; // arr1 сега е [0, 1, 2, 3, 4, 5]
+
+ +

{{jsxref("Array.prototype.unshift()")}} често се използва за добавяне на масив със стойности в началото на вече съществуващ масив. Без разпределящ синтаксис това може да бъде направено по следния начин: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+// Добавя всички елементи от arr2 преди тези на arr1
+Array.prototype.unshift.apply(arr1, arr2) // arr1 сега е [3, 4, 5, 0, 1, 2]
+ +

С разпределящ синтаксис става по следния начин: 

+ +
var arr1 = [0, 1, 2];
+var arr2 = [3, 4, 5];
+arr1 = [...arr2, ...arr1]; // arr1 сега е [3, 4, 5, 0, 1, 2]
+
+ +
+

Забележка: За разлика от unshift(), това създава нов arr1, а не модифицира оригиналния масив arr1

+
+ +

Разпределящ синтаксис при дефиниця на обекти

+ +

Предложението за Rest/Spread Properties for ECMAScript (етап 4) добавя разпределящи свойства към дефиницията на обекти. То копира собствени изброими свойства от даден обект към нов обект.

+ +

Повърхностното клониране(изключващо prototype) или смесването на обекти вече е възможно с помощта на по-кратък синтаксис от {{jsxref("Object.assign()")}}.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Обект { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Обект { foo: "baz", x: 42, y: 13 }
+ +

Обърнете внимание, че {{jsxref("Object.assign()")}} извиква setters за разлика от разпределящия синтаксис.

+ +

Забележете, че функцията  {{jsxref("Object.assign()")}} не може нито да бъде подменена, нито да се напише подобна:

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+const merge = ( ...objects ) => ( { ...objects } );
+
+var mergedObj = merge ( obj1, obj2);
+// Обект { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 13 } }
+
+var mergedObj = merge ( {}, obj1, obj2);
+// Обект { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 13 } }
+ +

В горния пример разпределящият синтаксис не работи както се очаква: той разпределя масив от аргументи в дефиницията на обекта според зададените параметри. 

+ +

Само за итериращи променливи

+ +

Разпределящият синтаксис (както и разпределящите свойства) може да бъде приложен само върху обекти, които могат да бъдат итерирани:

+ +
var obj = {'key1': 'value1'};
+var array = [...obj]; // TypeError: obj не може да се итерира
+
+ +

Разпределящ синтаксис с много стойности 

+ +

Когато използваме разпределящ синтаксис за извикване на функции трябва да бъдем запознати с възможността за надвишаване на лимита на брой на аргументи на функция в Javascript. За повече информация вижте {{jsxref("Function.prototype.apply", "apply()")}}.

+ +

Обединяващ синтаксис (параметри) 

+ +

Обединяващият синтаксис изглежда точно както разпределящия синтаксис, но е използван за разлагане на масиви и обекти. Иначе казано, обединяващият синтаксис е точно обратното на разпределящия синтаксис: докато разпределящият синтаксис разширява масива си със стойности, обединяващият синтаксис събира няколко елемента и ги събира в един елемент. За повече информация вижте rest parameters.

+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}Дефинирана в няколко секции на спецификацията: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Дефинирана в Object Initializer
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}Няма промени.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}Няма промени.
+ +

Съвместимост с браузъри

+ + + +

{{Compat("javascript.operators.spread")}}

+ +

Вижте още

+ + -- cgit v1.2.3-54-g00ecf