diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/pl/web/javascript/reference | |
parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip |
initial commit
Diffstat (limited to 'files/pl/web/javascript/reference')
25 files changed, 3844 insertions, 0 deletions
diff --git a/files/pl/web/javascript/reference/classes/extends/index.html b/files/pl/web/javascript/reference/classes/extends/index.html new file mode 100644 index 0000000000..6b25a766e5 --- /dev/null +++ b/files/pl/web/javascript/reference/classes/extends/index.html @@ -0,0 +1,88 @@ +--- +title: extends +slug: Web/JavaScript/Reference/Classes/extends +tags: + - Classes + - ECMAScript 2015 + - JavaScript +translation_of: Web/JavaScript/Reference/Classes/extends +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>Słowo kluczowe <strong><code>extends</code></strong> jest używane w <a href="/pl/docs/Web/JavaScript/Referencje/Polecenia/class">deklaracjach klas</a> lub <a href="/en-US/docs/Web/JavaScript/Reference/Operators/class">wyrażeniach class</a> do tworzenia klasy jako elementu potomnego innej klasy.</p> + +<div>{{EmbedInteractiveExample("pages/js/classes-extends.html")}}</div> + + + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">class ChildClass extends ParentClass { ... }</pre> + +<h2 id="Opis">Opis</h2> + +<p>Słowo kluczowe <code>extends</code> może być użyte do dziedziczenia po niestandardowych klasach lub standardowych obiektach wbudowanych.</p> + +<p>Prototypem rozszerzenia musi być {{jsxref("Object")}} lub {{jsxref("null")}}.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Zastosowanie_extends">Zastosowanie <code>extends</code></h3> + +<p>Pierwszy przykład tworzy klasę <code>Square</code> rozszerzającą klasę <code>Polygon</code>. <a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>.</p> + +<pre class="brush: js notranslate">class Square extends Polygon { + constructor(length) { + // Wywołanie konstruktora klasy nadrzędnej + // określenie szerokości i wysokości wielokątu + super(length, length); + // Uwaga: W pochodnych klasach, super() musi być wywołane wcześniej niż + // pierwsze użycie 'this'. W przeciwnym wypadku pojawi się błąd odniesienia. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } +}</pre> + +<h3 id="Zastosowanie_extends_z_obiektami_wbudowanymi">Zastosowanie <code>extends</code> z obiektami wbudowanymi</h3> + +<p>Poniższy przykład rozszerza wbudowany obiekt {{jsxref("Date")}}. <a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a> <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">(source)</a>.</p> + +<pre class="brush: js notranslate">class myDate extends Date { + + getFormattedDate() { + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear(); + } +} +</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność">Kompatybilność</h2> + + + +<p>{{Compat("javascript.classes.extends")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/pl/docs/Web/JavaScript/Reference/Classes">Classes</a></li> + <li><a href="/pl/docs/Web/JavaScript/Reference/Classes/Konstruktor">Konstruktor</a></li> + <li><a href="/pl/docs/Web/JavaScript/Referencje/Operatory/super">super</a></li> + <li><a href="https://medium.com/beginners-guide-to-mobile-web-development/super-and-extends-in-javascript-es6-understanding-the-tough-parts-6120372d3420">Anurag Majumdar - Super & Extends in JavaScript</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/classes/index.html b/files/pl/web/javascript/reference/classes/index.html new file mode 100644 index 0000000000..81388acbc3 --- /dev/null +++ b/files/pl/web/javascript/reference/classes/index.html @@ -0,0 +1,410 @@ +--- +title: Classes +slug: Web/JavaScript/Reference/Classes +tags: + - Classes + - Constructors + - ECMAScript 2015 + - Inheritance + - Intermediate + - JavaScript + - TopicStub +translation_of: Web/JavaScript/Reference/Classes +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>Klasy w Javascript zostały wprowadzone w ECMAScript 2015 jako lukier składniowy<strong> </strong>(ang. <em>syntactic sugar</em>) dla istniejącego, opartego na prototypach modelu dziedziczenia. Składnia klas <strong>nie</strong> wprowadza nowego zorientowanego obiektowo modelu dziedziczenia. Klasy wprowadzają znacznie prostszą i bardziej czytelną składnię do tworzenia obiektów i dziedziczenia.</p> + +<h2 id="Definiowanie_klas">Definiowanie klas</h2> + +<p>Klasy są w zasadzie "szczególnymi <a href="/pl/docs/Web/JavaScript/Reference/Functions">funkcjami</a>". Podobnie jak w funkcji można definiować <a href="/pl/docs/Web/JavaScript/Referencje/Operatory/Operator_function">wyrażenie <code>function</code></a> i <a href="/pl/docs/Web/JavaScript/Reference/Statements/function">deklaracje funkcji</a>, tak składnia klasy posiada dwa komponenty: <a href="/pl/docs/Web/JavaScript/Reference/Operators/class">wyrażenie <code>class</code></a> i <a href="/pl/docs/Web/JavaScript/Reference/Statements/class">deklaracje klasy</a>.</p> + +<h3 id="Deklaracje_klas">Deklaracje klas</h3> + +<p>Jednym ze sposobów definiowania klas jest <strong>deklaracja klasy</strong>. Aby zadeklarować klasę, należy użyć słowa kluczowego <code>class</code> wraz z nazwą klasy (w tym przypadku "Prostokat").</p> + +<pre class="brush: js notranslate">class Prostokat { + constructor(wysokosc, szerokosc) { + this.wysokosc = wysokosc; + this.szerokosc = szerokosc; + } +}</pre> + +<h4 id="Hoisting">Hoisting</h4> + +<p>Ważną różnicą pomiędzy <strong>deklaracją funkcji</strong> a <strong>deklaracją klasy</strong> jest to, że deklaracje funkcji są przenoszone na początek ({{Glossary("Hoisting")}}) a klas nie. Najpierw musisz zadeklarować swoją klasę, by mieć do niej dostęp, w przeciwnym razie kod, jak ten poniżej, wygeneruje błąd {{jsxref("ReferenceError")}}:</p> + +<pre class="brush: js example-bad notranslate">var p = new Prostokat(); // ReferenceError + +class Prostokat {} +</pre> + +<h3 id="Wyrażenie_class">Wyrażenie <code>class</code></h3> + +<p><strong>Wyrażenie <code>class</code></strong> jest kolejnym sposobem definiowania klasy. Wyrażenia <code>class</code> mogą być nazwane lub nienazwane. Nazwa przypisana nazwanemu wyrażeniu <code>class</code> jest lokalna dla ciała klasy. (można ją odczytać z właściwości {{jsxref("Function.name", "name")}} klasy)</p> + +<pre class="brush: js notranslate">// nienazwane +var Prostokat = class { + constructor(wysokosc, szerokosc) { + this.wysokosc = wysokosc; + this.szerokosc = szerokosc; + } +}; +console.log(Prostokat.name); // Prostokat + +// nazwane +var Prostokat = class Prostokat2 { + constructor(wysokosc, szerokosc) { + this.wysokosc = wysokosc; + this.szerokosc = szerokosc; + } +}; +console.log(Prostokat.name); // Prostokat2 +</pre> + +<div class="note"> +<p><strong>Uwaga</strong>: <strong>Wyrażenia </strong><code>class</code> dotykają te same kwestie związane z przenoszeniem na początek (ang. hoisting) co wspomnianych <strong>deklaracji </strong>klas.</p> +</div> + +<h2 id="Ciało_klasy_i_definicje_metod">Ciało klasy i definicje metod</h2> + +<p>Ciało klasy jest umieszczane w nawiasach klamrowych <code>{}</code>. To tam definiuje się metody, czy konstruktory.</p> + +<h3 id="Tryb_ścisły">Tryb ścisły</h3> + +<p>Ciało klasy jest wykonywane w <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">trybie ścisłym</a> (ang. <em>strict mode</em>). W celu poprawienia wydajności, kod wykorzystywany tutaj podlega ścisłej składni; nie pozwala to na ukrycie niektórych wyjątków, a pewne słowa kluczowe są rezerwowane dla przyszłych wersji ECMAScript.</p> + +<h3 id="Konstruktor">Konstruktor</h3> + +<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/constructor">Constructor</a></code> jest szczególną metodą, która służy tworzeniu i inicjalizowaniu obiektu zdefiniowanego słowem kluczowym <code>class</code>. Dozwolony jest tylko jeden konstruktor w danej klasie. Jeśli klasa posiada więcej niż jedno wystąpienie metody <code>constructor</code>, wygenerowany zostanie błąd {{jsxref("SyntaxError")}}.</p> + +<p>Aby wywołać konstruktor klasy bazowej, należy użyć słowa kluczowego <code>super</code>.</p> + +<h3 id="Metody">Metody</h3> + +<p>Zobacz też <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">definiowanie metod</a>.</p> + +<pre class="brush: js notranslate">class Prostokat { + constructor(wysokosc, szerokosc) { + this.wysokosc = wysokosc; + this.szerokosc = szerokosc; + } + // Getter + get pole() { + return this.liczPole(); + } + // Method + liczPole() { + return this.wysokosc * this.szerokosc; + } +} + +const kwadrat = new Prostokat(10, 10); + +console.log(kwadrat.pole); // 100</pre> + +<h3 id="Metody_i_właściwości_statyczne">Metody i właściwości statyczne</h3> + +<p>Słowo kluczowe <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/static">static</a></code> definiuje metodę kub właściwość statyczną w klasie. Statyczne metody i właściwości są wywoływane bez <a href="/pl/docs/Learn/JavaScript/Obiekty" title='An example of class instance is "var john = new Person();"'>inicjalizowania</a> ich klas i <strong>nie mogą</strong> być wywołane przez instancję klasy.</p> + +<pre class="brush: js notranslate">class Punkt { + constructor(x, y) { + this.x = x; + this.y = y; + } + + static nazwa = "Punkt"; + static odleglosc(a, b) { + const dx = a.x - b.x; + const dy = a.y - b.y; + + return Math.sqrt(dx*dx + dy*dy); + } +} + +const p1 = new Punkt(5, 5); +const p2 = new Punkt(10, 10); +p1.nazwa; // undefined +p1.odleglosc; // undefined +p2.nazwa; // undefined +p2.odleglosc; // undefined + +console.log(Punkt.nazwa); // "Punkt" +console.log(Punkt.odleglosc(p1, p2)); // 7.0710678118654755</pre> + +<h3 id="Powiązanie_this_z_metodami_niestatycznymi_i_statycznymi">Powiązanie <code>this</code> z metodami niestatycznymi i statycznymi</h3> + +<p>Kiedy metoda typu <code>static</code> lub <code>prototype</code> jest wywoływana bez <code>this</code> (na przykład poprzez przypisanie metody do zmiennej), wtedy <code>this</code><em> </em>będzie <code>undefined</code> w środku metody. Takie zachowanie będzie takie same, nawet jeżeli dyrektywa <code>"use strict"</code> nie będzie obecna, ponieważ kod w obrębie metody danej klasy zawsze będzie wykonywał się jako <code>strict mode</code>.</p> + +<pre class="brush: js notranslate">class Animal { + speak() { + return this; + } + static eat() { + return this; + } +} + +let obj = new Animal(); +obj.speak(); // obiekt Animal +let speak = obj.speak; +speak(); // undefined + +Animal.eat(); // klasa Animal +let eat = Animal.eat; +eat(); // undefined</pre> + +<p>Jeśli przepiszemy powyższy przykład z użyciem tradycyjnych funkcji bez dyrektywy <code>"use strict"</code>, to <code>this</code> wywołane w metodzie będzie automatycznie przypisane do pierwotnej wartości <code>this</code>, którą domyślnie jest <a href="/en-US/docs/Glossary/Global_object">global object</a>.</p> + +<pre class="brush: js notranslate">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 +</pre> + +<h3 id="Właściwości_instancji">Właściwości instancji</h3> + +<p>Właściwości instancji muszą być zdefiniowane wewnątrz metody klasy:</p> + +<pre class="brush: js notranslate">class Rectangle { + constructor(height, width) { + this.height = height; + this.width = width; + } +}</pre> + +<p>Statyczne właściwości i właściwości prototypu muszą być zdefiniowane poza ciałem klasy:</p> + +<pre class="brush: js notranslate">Rectangle.staticWidth = 20; +Rectangle.prototype.prototypeWidth = 25;</pre> + +<h3 id="Deklaracje_pól">Deklaracje pól</h3> + +<div class="blockIndicator warning"> +<p>Publiczna i prywatne deklaracje pól są <a href="https://github.com/tc39/proposal-class-fields">funkcjonalnościami eksperymentalnymi</a> zaproponowanymi na <a href="https://tc39.es">TC39</a>. Wsparcie przeglądarek jest ograniczone, ale ta funkcjonalność może być używana przy użyciu systemów takich jak <a href="https://babeljs.io/">Babel</a>. </p> +</div> + +<h4 id="Deklaracje_pól_publicznych">Deklaracje pól publicznych</h4> + +<p>Przy użyciu deklaracji pól, powyższy przykład może być przepisany na:</p> + +<pre class="brush: js notranslate">class Rectangle { + height = 0; + width; + constructor(height, width) { + this.height = height; + this.width = width; + } +} +</pre> + +<p>Dzięki deklarowaniu pól na początku klasy, definicje klas stają się bardziej samodokumentujące, a pola są zawsze obecne.</p> + +<p>Jak widać w powyższym przykładzie, pola mogą być zadeklarowane z lub bez domyślnej wartości.</p> + +<p>Zobacz <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields">public class fields</a> po więcej informacji.</p> + +<h4 id="Deklaracje_pól_prywatnych">Deklaracje pól prywatnych</h4> + +<p>Używając deklaracji pól prywatnych, definicja może być zapisana w taki sposób:</p> + +<pre class="brush: js notranslate">class Rectangle { + #height = 0; + #width; + constructor(height, width) { + this.#height = height; + this.#width = width; + } +} +</pre> + +<p>Próba odniesienia się do prywatnego pola poza ciałem klasy wygeneruje błąd. Prywatne pola mogą być tylko odczytywane i modyfikowane wewnątrz ciała klasy. Poprzez definicję właściwości niewidocznych poza ciałem klasy, można zapewnić, że użytkownicy klasy nie będą polegali na jej wewnętrznych właściwościach.</p> + +<div class="note"> +<p>Pola prywatne mogą być tylko zadeklarowane na początku ciała klasy</p> +</div> + +<p>Prywatnych pól nie da się utworzyć później, poprzez przypisywanie, tak jak normalnych właściwości.</p> + +<p>Po więcej informacji zobacz <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">private class fields</a>.</p> + +<h2 id="Podklasy_z_extends">Podklasy z <code>extends</code></h2> + +<p>Słowo kluczowe <code><a href="/en-US/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> jest używane w <em>deklaracjach klas</em> lub <em>wyrażeniach klas</em> do tworzenia klasy jako elementu potomnego innej klasy.</p> + +<pre class="brush: js notranslate">class Animal { + constructor(name) { + this.name = name; + } + + speak() { + console.log(this.name + ' makes a noise.'); + } +} + +class Dog extends Animal { + constructor(name) { + super(name); // wywyłanie konstruktora klasy nadrzędnej poprzez użycie super() + } + speak() { + console.log(this.name + ' barks.'); + } +} + +let d = new Dog('Mitzie'); +d.speak(); // Mitzie barks. +</pre> + +<p>Jeśli w podklasie znajduje się konstruktor, musi najpierw wywołać super() przed użyciem "this".</p> + +<p>Można również rozszerzyć tradycyjne klasy oparte na funkcjach:</p> + +<pre class="brush: js notranslate">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 +</pre> + +<p>Zwróć uwagę, że klasy nie mogą rozszerzać zwykłych (niezdatnych do konstrukcji) obiektów. Jeśli chcesz dziedziczyć po zwykłym obiekcie, możesz, zamiast tego użyć {{jsxref ("Object.setPrototypeOf()")}}:</p> + +<pre class="brush: js notranslate">var Animal = { + speak() { + console.log(this.name + ' makes a noise.'); + } +}; + +class Dog { + constructor(name) { + this.name = name; + } +} + +Object.setPrototypeOf(Dog.prototype, Animal);// If you do not do this you will get a TypeError when you invoke speak + +let d = new Dog('Mitzie'); +d.speak(); //Mitzie makes a noise. +</pre> + +<h2 id="Species">Species</h2> + +<p>Jeśli chcesz zwrócić obiekt {{jsxref("Array")}} w twojej klasie <code>MyArray</code>, która dziedziczy po <code>Array</code>, to możesz użyć wzorca "species", który pozwala na nadpisywanie domyślnych konstruktorów.</p> + +<p>Na przykład, wywołanie metody {{jsxref("Array.map", "map()")}} zwraca domyślny konstruktor <code>MyArray</code>. Użycie {{jsxref("Symbol.species")}} pozwala na nadpisanie tego zachowania tak, by zwracany był obiekt typu <code>Array</code>, a nie <code>MyArray</code>:</p> + +<pre class="brush: js notranslate">class MyArray extends Array { + // Nadpisanie domyślnego kontruktora + static get [Symbol.species]() { return Array; } +} + +var a = new MyArray(1,2,3); +var mapped = a.map(x => x * x); + +console.log(mapped instanceof MyArray); // false +console.log(mapped instanceof Array); // true +</pre> + +<h2 id="Słowo_kluczowe_super">Słowo kluczowe <code>super</code></h2> + +<p>Słowo kluczowe <strong>super </strong>jest wykorzystywane do udostępniania i korzystania z funkcji klasy, po której nasz obiekt dziedziczy.</p> + +<pre class="brush: js notranslate">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.</pre> + +<h2 id="Mix-ins">Mix-ins</h2> + +<p>Abstrakcyjne podklasy lub <em>mix-ins</em> są szablonami dla klas. Klasa może mieć tylko jedną klasę nadrzędną, więc dziedziczenie z wielu klas jest niemożliwe. Cała funkcjonalność musi być dostarczona przez jedną klasę nadrzędną.</p> + +<p>Funkcja przyjmująca klasę nadrzędną jako argument i zwracająca podklasę rozszerzającą klasę nadrzędną może być użyta do implementacji mix-in'ów:</p> + +<pre class="brush: js notranslate">var calculatorMixin = Base => class extends Base { + calc() { } +}; + +var randomizerMixin = Base => class extends Base { + randomize() { } +}; +</pre> + +<p>Klasa używająca tych mix-in'ów może być zapisana w taki sposób:</p> + +<pre class="brush: js notranslate">class Foo { } +class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + <th scope="col">Status</th> + <th scope="col">Komentarz</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność">Kompatybilność</h2> + +<p>{{Compat("javascript.classes")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li>{{jsxref("Operators/super", "super")}}</li> + <li><a href="https://hacks.mozilla.org/2015/07/es6-in-depth-classes/">Blog post: "ES6 In Depth: Classes"</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/classes/konstruktor/index.html b/files/pl/web/javascript/reference/classes/konstruktor/index.html new file mode 100644 index 0000000000..353adecd19 --- /dev/null +++ b/files/pl/web/javascript/reference/classes/konstruktor/index.html @@ -0,0 +1,188 @@ +--- +title: Konstruktor +slug: Web/JavaScript/Reference/Classes/Konstruktor +tags: + - Classes + - JavaScript + - Language feature +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>Konstruktor <span id="result_box" lang="pl"><span>jest specjalną metodą tworzenia i inicjowania obiektu utworzonego w klasie.</span></span></p> + +<p>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</p> + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">constructor([arguments]) { ... }</pre> + +<h2 id="Opis">Opis</h2> + +<p>Konstruktor umożliwia zdefiniowanie inicjalizacji obiektu, która musi się wykonać, zanim będzie można wywołać metody obiektu.</p> + +<pre class="brush: js notranslate">class Person { + + constructor(name) { + this.name = name; + } + + introduce() { + console.log(`Hello, my name is ${this.name}`); + } + +} + +const otto = new Person('Otto'); + +otto.introduce();</pre> + +<p>Jeśli niestandardowy konstruktor nie został podany, to domyślny konstruktor będzie użyty. Dla klas bazowych konstruktor domyślny jest pusty:</p> + +<pre class="brush: js notranslate">constructor() {}</pre> + +<p>Dla klas pochodnych domyślny konstruktor wywołuje konstruktor klasy nadrzędnej:</p> + +<pre class="brush: js notranslate">constructor(...args) { + super(...args); +}</pre> + +<p>Pozwala to na działanie takiego kodu:</p> + +<pre class="brush: js notranslate">class ValidationError extends Error { + + printCustomerMessage() { + return `Validation failed :-( (details: ${this.message})`; + } + +} + +try { + throw new ValidationError("Not a valid phone number"); +} catch (error) { + if (error instanceof ValidationError) { + console.log(error.name); // This is Error instead of ValidationError! + console.log(error.printCustomerMessage()); + } else { + console.log('Unknown error', error); + throw error; + } +}</pre> + +<p>Klasa <code>ValidationError</code> nie musi mieć niestandardowego konstruktora, ponieważ domyślny konstruktor wywołuje konstruktor klasy <code>Error</code>.</p> + +<p>Jeśli jednak klasa <code>ValidationError</code> ma niestandardowy konstruktor, to musi on wywoływać konstruktor klasy nadrzędnej przy użyciu <code>super</code>:</p> + +<pre class="brush: js notranslate">class ValidationError extends Error { + + constructor(message) { + super(message); // call parent class constructor + this.name = 'ValidationError'; + this.code = '42'; + } + + printCustomerMessage() { + return `Validation failed :-( (details: ${this.message}, code: ${this.code})`; + } + +} + +try { + throw new ValidationError("Not a valid phone number"); +} catch (error) { + if (error instanceof ValidationError) { + console.log(error.name); // Now this is ValidationError! + console.log(error.printCustomerMessage()); + } else { + console.log('Unknown error', error); + throw error; + } +}</pre> + +<p>Wewnątrz klasy może być tylko jedna metoda nazwana <code>constructor</code>. Jeżeli <code>constructor</code> wystąpi więcej niż jeden raz, to wygeneruje błąd {{jsxref("SyntaxError")}}.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Używanie_konstruktora">Używanie konstruktora</h3> + +<p>Fragment kodu pochodzi z <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>).</p> + +<pre class="brush: js notranslate">class Square extends Polygon { + constructor(length) { + // Wywołanie konstruktora klasy nadrzędnej + // określenie szerokości i wysokości wielokątu + super(length, length); + // Uwaga: W pochodnych klasach, super() musi być wywołane wcześniej niż + // pierwsze użycie 'this'. W przeciwnym wypadku pojawi się błąd odniesienia. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="Inny_przykład">Inny przykład</h3> + +<p>W tym przykładzie klasa <code>Square</code> jest zmieniona — ale konstruktor klasy <code>Polygon</code> nadal jest wywoływany przy tworzeniu nowej instancji klasy <code>Square</code>.</p> + +<pre class="brush: js notranslate">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</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + <th scope="col">Status</th> + <th scope="col">Komentarz</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność">Kompatybilność</h2> + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/classes/private_class_fields/index.html b/files/pl/web/javascript/reference/classes/private_class_fields/index.html new file mode 100644 index 0000000000..6b55474d5b --- /dev/null +++ b/files/pl/web/javascript/reference/classes/private_class_fields/index.html @@ -0,0 +1,205 @@ +--- +title: Private class fields +slug: Web/JavaScript/Reference/Classes/Private_class_fields +tags: + - Classes + - JavaScript + - Language feature +translation_of: Web/JavaScript/Reference/Classes/Private_class_fields +--- +<div>{{JsSidebar("Classes")}}</div> + +<p>Właściwości klas są domyślnie publiczne i mogą być wywoływane i modyfikowane poza klasą. Istnieje jednak <a href="https://github.com/tc39/proposal-class-fields">funkcjonalność eksperymentalna</a> pozwalająca na zdefiniowanie pól prywatnych klasy przy użyciu <code>#</code> przed nazwą pola.</p> + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">class ClassWithPrivateField { + #privateField +} + +class ClassWithPrivateMethod { + #privateMethod() { + return 'hello world' + } +} + +class ClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD +} +</pre> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Prywatne_pola_statyczne">Prywatne pola statyczne</h3> + +<p>Pola prywatne są dostępne z poziomu konstruktora klasy ze środka ciała klasy.</p> + +<p>Prywatne pola statyczne są tylko dostępne z poziomu statycznych metod. </p> + +<pre class="brush: js notranslate">class ClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static publicStaticMethod() { + ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD = 42 + return ClassWithPrivateStaticField.#PRIVATE_STATIC_FIELD + } +} + +console.assert(ClassWithPrivateStaticField.publicStaticMethod() === 42)</pre> + +<p>Prywatne pola statyczne są dodawane do konstruktora klasy podczas wykonywania klasy.</p> + +<p>Tylko klasa, która definiuje prywatne pola statyczne, może mieć do nich dostęp.</p> + +<p>Może to prowadzić to nieoczekiwanego zachowania podczas używania <strong><code>this</code></strong>.</p> + +<pre class="brush: js notranslate">class BaseClassWithPrivateStaticField { + static #PRIVATE_STATIC_FIELD + + static basePublicStaticMethod() { + this.#PRIVATE_STATIC_FIELD = 42 + return this.#PRIVATE_STATIC_FIELD + } +} + +class SubClass extends BaseClassWithPrivateStaticField { } + +let error = null + +try { + SubClass.basePublicStaticMethod() +} catch(e) { error = e} + +console.assert(error instanceof TypeError) +</pre> + +<h3 id="Prywatne_pola_instancji">Prywatne pola instancji</h3> + +<p>Prywatne pola instancji są deklarowane przy użyciu <strong># names </strong>("<em>hash names</em>"), czyli nazw poprzedzonych <code>#</code>. Znak <code>#</code> jest częścią nazwy. Jest używany do deklaracji i dostępu do właściwości.</p> + +<p>Enkapsulacja jest wymuszona przez język. Próba dostępu do prywatnego pola poza klasą wygeneruje błąd <code>Syntax Error</code>.</p> + +<pre class="brush: js notranslate">class ClassWithPrivateField { + #privateField + + constructor() { + this.#privateField = 42 + this.#randomField = 444 // Syntax error + } +} + +const instance = new ClassWithPrivateField() +instance.#privateField === 42 // Syntax error +</pre> + +<h3 id="Prywatne_metody">Prywatne metody</h3> + +<h4 id="Prywatne_metody_statyczne">Prywatne metody statyczne</h4> + +<p>Podobnie jak ich publiczne odpowiedniki, prywatne metody statyczne są wywoływane przez samą klasę, a nie jej instancje. Podobnie jak pola prywatne, są dostępne tylko z poziomu ciała klasy.</p> + +<pre class="brush: js notranslate">class ClassWithPrivateStaticMethod { + static #privateStaticMethod() { + return 42 + } + + static publicStaticMethod1() { + return ClassWithPrivateStaticMethod.#privateStaticMethod(); + } + + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +console.assert(ClassWithPrivateStaticMethod.publicStaticMethod1() === 42); +console.assert(ClassWithPrivateStaticMethod.publicStaticMethod2() === 42); +</pre> + +<p>Może to prowadzić do nieoczekiwanego zachowania przy używaniu <strong><code>this</code></strong>. W poniższym przykładzie <code>this</code> odnosi się do klasy <code>Derived</code> (a nie klasy <code>Base</code>) podczas wywołania metody <code>Derived.publicStaticMethod2()</code>, co powoduje błąd.</p> + +<pre class="brush: js notranslate">class Base { + static #privateStaticMethod() { + return 42; + } + static publicStaticMethod1() { + return Base.#privateStaticMethod(); + } + static publicStaticMethod2() { + return this.#privateStaticMethod(); + } +} + +class Derived extends Base {} + +console.log(Derived.publicStaticMethod1()); // 42 +console.log(Derived.publicStaticMethod2()); // TypeError +</pre> + +<h4 id="Prywatne_metody_instancji">Prywatne metody instancji</h4> + +<p>Prywatne metody instancji to metody dostępne dla instancji klasy, które mają podobne ograniczenia co prywatne pola instancji.</p> + +<pre class="brush: js notranslate">class ClassWithPrivateMethod { + #privateMethod() { + return 'hello world' + } + + getPrivateMessage() { + return this.#privateMethod() + } +} + +const instance = new ClassWithPrivateMethod() +console.log(instance.getPrivateMessage()) +// expected output: "hello world"</pre> + +<p>Prywatne metody mogą używać async lub być generatorami. Możliwe jest również tworzenie prywatnych getter'ów i setter'ów:</p> + +<pre class="brush: js notranslate">class ClassWithPrivateAccessor { + #message + + get #decoratedMessage() { + return `✨${this.#message}✨` + } + set #decoratedMessage(msg) { + this.#message = msg + } + + constructor() { + this.#decoratedMessage = 'hello world' + console.log(this.#decoratedMessage) + } +} + +new ClassWithPrivateAccessor(); +// expected output: "✨hello world✨" +</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specyfikacja</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Public and private instance fields', '#prod-FieldDefinition', 'FieldDefinition')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność_2"><a id="Kompatybilność" name="Kompatybilność">Kompatybilność</a></h2> + + + +<p>{{Compat("javascript.classes.private_class_fields")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/pl/docs/Web/JavaScript/Reference/Classes/Public_class_fields">Public class fields</a></li> + <li><a href="https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html">The Semantics of All JS Class Elements</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/classes/public_class_fields/index.html b/files/pl/web/javascript/reference/classes/public_class_fields/index.html new file mode 100644 index 0000000000..780300e64f --- /dev/null +++ b/files/pl/web/javascript/reference/classes/public_class_fields/index.html @@ -0,0 +1,269 @@ +--- +title: Public class fields +slug: Web/JavaScript/Reference/Classes/Public_class_fields +tags: + - Classes + - JavaScript + - Language feature +translation_of: Web/JavaScript/Reference/Classes/Public_class_fields +--- +<div>{{JsSidebar("Classes")}}</div> + +<div> +<div class="note"> +<p><strong>Ta strona opisuje funkcjonalności eksperymentalne</strong></p> + +<p>Deklaracje pól publicznych i prywatnych są <a class="external external-icon" href="https://github.com/tc39/proposal-class-fields" rel="noopener">funkcjonalnościami eksperymentalnymi (stage 3)</a> zaproponowanymi na <a class="external external-icon" href="https://tc39.github.io/beta/" rel="noopener">TC39</a>.</p> + +<p>Wsparcie przeglądarek jest ograniczone, ale ta funkcjonalność może być używana przy użyciu systemów takich jak <a class="external external-icon" href="https://babeljs.io/" rel="noopener">Babel</a>. Zobacz <a href="#Kompatybilność">tabelę kompatybilności</a> poniżej.</p> +</div> +</div> + +<p>Zarówno statyczne, jak i instancyjne pola publiczne są właściwościami zapisywalnymi, wyliczalnymi i konfigurowalnymi. W przeciwieństwie do ich prywatnych odpowiedników uczestniczą w dziedziczeniu prototypów.</p> + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">class ClassWithInstanceField { + instanceField = 'instance field' +} + +class ClassWithStaticField { + static staticField = 'static field' +} + +class ClassWithPublicInstanceMethod { + publicMethod() { + return 'hello world' + } +} +</pre> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Publiczne_pola_statyczne">Publiczne pola statyczne</h3> + +<p>Publiczne pola statyczne są użyteczne, gdy chcesz, aby pole istniało tylko raz dla danej klasy, a nie dla każdej tworzonej instancji klasy. Jest to użyteczne w przypadku cache'ów, stałej konfiguracji lub innych danych, które nie muszą być replikowane na wszystkich instancjach.</p> + +<p>Publiczne pola statyczne są deklarowane z użyciem słowa kluczowego <code>static</code>. Są dodawane do konstruktora klasy podczas jej wykonywania z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. Są one dostępne z poziomu konstruktora klasy.</p> + +<pre class="brush: js notranslate">class ClassWithStaticField { + static staticField = 'static field' +} + +console.log(ClassWithStaticField.staticField) +// expected output: "static field" +</pre> + +<p>Pola bez inicjalizatorów są ustawiane na <code>undefined</code>.</p> + +<pre class="brush: js notranslate">class ClassWithStaticField { + static staticField +} + +console.assert(ClassWithStaticField.hasOwnProperty('staticField')) +console.log(ClassWithStaticField.staticField) +// expected output: "undefined"</pre> + +<p>Publiczne pola statyczne nie są inicjalizowane ponownie w podklasach, ale można uzyskać do nich dostęp przez łańcuch prototypów.</p> + +<pre class="brush: js notranslate">class ClassWithStaticField { + static baseStaticField = 'base field' +} + +class SubClassWithStaticField extends ClassWithStaticField { + static subStaticField = 'sub class field' +} + +console.log(SubClassWithStaticField.subStaticField) +// expected output: "sub class field" + +console.log(SubClassWithStaticField.baseStaticField) +// expected output: "base field"</pre> + +<p>Przy inicjalizacji pól, <code>this</code> odnosi się do konstruktora klasy. Można się również odwołać przez nazwę i użyć <code>super</code> do otrzymania konstruktora klasy nadrzędnej (jeżeli istnieje).</p> + +<pre class="brush: js notranslate">class ClassWithStaticField { + static baseStaticField = 'base static field' + static anotherBaseStaticField = this.baseStaticField + + static baseStaticMethod() { return 'base static method output' } +} + +class SubClassWithStaticField extends ClassWithStaticField { + static subStaticField = super.baseStaticMethod() +} + +console.log(ClassWithStaticField.anotherBaseStaticField) +// expected output: "base static field" + +console.log(SubClassWithStaticField.subStaticField) +// expected output: "base static method output" +</pre> + +<h3 id="Publiczne_pola_instancyjne">Publiczne pola instancyjne</h3> + +<p>Publiczne pola instancyjne istnieją na każdej utworzonej instancji danej klasy. Poprzez zadeklarowanie pola publicznego, można zapewnić, że pole jest zawsze obecne, a definicja klasy jest bardziej samodokumentująca.</p> + +<p>Publiczne pola instancyjne są dodawane przy użyciu {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonywania konstruktora klasy, lub po wywołaniu metody <code>super()</code>.</p> + +<pre class="brush: js notranslate">class ClassWithInstanceField { + instanceField = 'instance field' +} + +const instance = new ClassWithInstanceField() +console.log(instance.instanceField) +// expected output: "instance field"</pre> + +<p>Pola bez inicjalizatorów są ustawiane na <code>undefined</code>.</p> + +<pre class="brush: js notranslate">class ClassWithInstanceField { + instanceField +} + +const instance = new ClassWithInstanceField() +console.assert(instance.hasOwnProperty('instanceField')) +console.log(instance.instanceField) +// expected output: "undefined"</pre> + +<p>Podobnie jak właściwości, nazwy pól mogą być obliczane.</p> + +<pre class="brush: js notranslate">const PREFIX = 'prefix' + +class ClassWithComputedFieldName { + [`${PREFIX}Field`] = 'prefixed field' +} + +const instance = new ClassWithComputedFieldName() +console.log(instance.prefixField) +// expected output: "prefixed field"</pre> + +<p>Przy inicjalizacji pól <code>this</code> odnosi się do instancji klasy. Tak jak w publicznych metodach instancji, można odnieść się do klasy nadrzędnej, używając <code>super</code>.</p> + +<pre class="brush: js notranslate">class ClassWithInstanceField { + baseInstanceField = 'base field' + anotherBaseInstanceField = this.baseInstanceField + baseInstanceMethod() { return 'base method output' } +} + +class SubClassWithInstanceField extends ClassWithInstanceField { + subInstanceField = super.baseInstanceMethod() +} + +const base = new ClassWithInstanceField() +const sub = new SubClassWithInstanceField() + +console.log(base.anotherBaseInstanceField) +// expected output: "base field" + +console.log(sub.subInstanceField) +// expected output: "base method output"</pre> + +<h3 id="Publiczne_metody">Publiczne metody</h3> + +<h4 id="Publiczne_metody_statyczne">Publiczne metody statyczne</h4> + +<p>Słowo kluczowe <code><strong>static</strong></code> definiuje metodę statyczną dla klasy. Metody statyczne nie są wywoływane na instancjach klasy, ale na samej klasie. Są to często funkcje użytkowe, takie jak funkcje tworzenia lub klonowania obiektów.</p> + +<pre class="brush: js notranslate">class ClassWithStaticMethod { + static staticMethod() { + return 'static method has been called.'; + } +} + +console.log(ClassWithStaticMethod.staticMethod()); +// expected output: "static method has been called."</pre> + +<p>Metody statyczne są dodawane do konstruktora klasy z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonania klasy. Te metody są zapisywalne, niewyliczalne i konfigurowalne.</p> + +<h4 id="Publiczne_metody_instancyjne">Publiczne metody instancyjne</h4> + +<p>Jak nazwa wskazuje, publiczne metody instancji to metody dostępne na instancjach klasy.</p> + +<pre class="brush: js notranslate">class ClassWithPublicInstanceMethod { + publicMethod() { + return 'hello world' + } +} + +const instance = new ClassWithPublicInstanceMethod() +console.log(instance.publicMethod()) +// expected output: "hello world"</pre> + +<p>Publiczne metody instancji są dodawane do prototypu klasy z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonania klasy. Te metody są zapisywalne, niewyliczalne i konfigurowalne.</p> + +<p>Publiczne metody mogą używać async lub być generatorami.</p> + +<pre class="brush: js notranslate">class ClassWithFancyMethods { + *generatorMethod() { } + async asyncMethod() { } + async *asyncGeneratorMethod() { } +}</pre> + +<p>Wewnątrz metod instancji, <code>this</code> odnosi się do samej instancji. W podklasach można użyć <code>super</code> do dostępu do prototypu klasy nadrzędnej, umożliwiając wywoływanie metod tej klasy.</p> + +<pre class="brush: js notranslate">class BaseClass { + msg = 'hello world' + basePublicMethod() { + return this.msg + } +} + +class SubClass extends BaseClass { + subPublicMethod() { + return super.basePublicMethod() + } +} + +const instance = new SubClass() +console.log(instance.subPublicMethod()) +// expected output: "hello world" +</pre> + +<p>Getter'y i setter'y to specjalne metody, które wiążą się z właściwością danej klasy i są wywoływane, gdy właściwość jest odczytywana lub modyfikowana. Do tworzenia getter'ów i setter'ów należy użyć <a href="https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Functions/get">get</a> and <a href="https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Functions/set">set</a>.</p> + +<pre class="brush: js notranslate">class ClassWithGetSet { + #msg = 'hello world' + get msg() { + return this.#msg + } + set msg(x) { + this.#msg = `hello ${x}` + } +} + +const instance = new ClassWithGetSet() +console.log(instance.msg) +// expected output: "hello world" + +instance.msg = 'cake' +console.log(instance.msg) +// expected output: "hello cake" +</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specyfikacja</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Public and private instance fields', '#prod-FieldDefinition', 'FieldDefinition')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność_2"><a name="Kompatybilność">Kompatybilność</a></h2> + + + +<p>{{Compat("javascript.classes.public_class_fields")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/pl/docs/Web/JavaScript/Reference/Classes/Private_class_fields">Private class fields</a></li> + <li><a href="https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html">The Semantics of All JS Class Elements</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/classes/static/index.html b/files/pl/web/javascript/reference/classes/static/index.html new file mode 100644 index 0000000000..814c118957 --- /dev/null +++ b/files/pl/web/javascript/reference/classes/static/index.html @@ -0,0 +1,138 @@ +--- +title: static +slug: Web/JavaScript/Reference/Classes/static +tags: + - Classes + - ECMAScript 2015 + - JavaScript + - Static +translation_of: Web/JavaScript/Reference/Classes/static +--- +<div>{{jsSidebar("Classes")}}</div> + +<p><span class="seoSummary">Słowo kluczowe <code><strong>static</strong></code> definiuje statyczną metodę lub właściwość klasy. Metody i właściwości statyczne nie są wywoływane na instancjach klasy, a bezpośrednio na samej klasie. Statyczne metody to często funkcje służące na przykład do tworzenia czy klonowania obiektów, a statyczne właściwości są użyteczne do cache'ów, stałej konfiguracji lub innych właściwości, które nie muszą być powielane w instancjach.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/classes-static.html")}}</div> + + + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">static nazwaMetody() { ... } +static nazwaWlasciwosci [=wartosc]; +</pre> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Używanie_static_w_klasach">Używanie <code>static</code> w klasach</h3> + +<p>Poniższy przykład demonstruje kilka rzeczy:</p> + +<ol> + <li>Jak statyczna metoda lub właściwość jest implementowana w klasie</li> + <li>Klasa z metodą lub właściwością statyczną może być dziedziczona</li> + <li>Jak metoda lub właściwość statyczna może być wywoływana</li> +</ol> + +<pre class="brush: js notranslate">class Triple { + static customName = 'Tripler'; + static description = 'I triple any number you provide'; + static triple(n = 1) { + return n * 3; + } +} + +class BiggerTriple extends Triple { + static longDescription; + static description = 'I square the triple of any number you provide'; + static triple(n) { + return super.triple(n) * super.triple(n); + } +} + +console.log(Triple.description); // 'I triple any number you provide' +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(BiggerTriple.description); // 'I square the triple of any number you provide' +console.log(BiggerTriple.longDescription); // undefined +console.log(BiggerTriple.customName); // 'Tripler' + +console.log(tp.triple()); // 'tp.triple is not a function'. +</pre> + +<h3 id="Wywoływanie_metod_statycznych_z_innych_metod_statycznych">Wywoływanie metod statycznych z innych metod statycznych</h3> + +<p>W celu wywołania metody lub właściwości statycznej z innej metody statycznej tej samej klasy można użyć słowa kluczowego <code>this</code>.</p> + +<pre class="brush: js notranslate">class StaticMethodCall { + static staticProperty = 'static property'; + static staticMethod() { + return 'Static method and ' + this.staticProperty + ' has been called'; + } + static anotherStaticMethod() { + return this.staticMethod() + ' from another static method'; + } +} +StaticMethodCall.staticMethod(); +// 'Static method and static property has been called' + +StaticMethodCall.anotherStaticMethod(); +// 'Static method and static property has been called from another static method'</pre> + +<h3 id="Wywoływanie_metod_statycznych_z_konstruktora_i_innych_metod">Wywoływanie metod statycznych z konstruktora i innych metod</h3> + +<p>Metody statyczne nie są dostępne przez this w metodach niestatycznych. Trzeba je wywołać, używając nazwy klasy: <code>CLASSNAME.STATIC_METHOD_NAME()</code> / <code>CLASSNAME.STATIC_PROPERTY_NAME</code> lub jako metody właściwości <code>constructor</code>: <code>this.constructor.STATIC_METHOD_NAME()</code> / <code>this.constructor.STATIC_PROPERTY_NAME</code>.</p> + +<pre class="brush: js notranslate">class StaticMethodCall { + constructor() { + console.log(StaticMethodCall.staticProperty); // 'static property' + console.log(this.constructor.staticProperty); // 'static property' + console.log(StaticMethodCall.staticMethod()); // 'static method has been called.' + console.log(this.constructor.staticMethod()); // 'static method has been called.' + } + + static staticProperty = 'static property'; + static staticMethod() { + return 'static method has been called.'; + } +}</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + <th scope="col">Status</th> + <th scope="col">Komentarz</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Definicja początkowa.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność">Kompatybilność</h2> + + + +<p>{{Compat("javascript.classes.static")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/brakujący_średnik_po_własności_id/index.html b/files/pl/web/javascript/reference/errors/brakujący_średnik_po_własności_id/index.html new file mode 100644 index 0000000000..ecdb783335 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/brakujący_średnik_po_własności_id/index.html @@ -0,0 +1,77 @@ +--- +title: 'Błąd składni: brakująca własność po identyfikatorze.' +slug: Web/JavaScript/Reference/Errors/Brakujący_średnik_po_własności_id +tags: + - Błąd + - Błąd składniowy + - Błędy + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox"><span class="short_text" id="result_box" lang="pl"><span>Błąd składni: brakująca własność po identyfikatorze.</span></span> +</pre> + +<h2 id="Typ_błedu">Typ błedu</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Kiedy tworzysz objekty korzystając z <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Inicjalizatora objektu</a> składnia, używając dwukropka (<code>:</code>) oddziela klucze i wartości od własności objektu.</p> + +<pre class="brush: js">var obj = { własnośćKlucza: 'wartość' }; +</pre> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Dwukropki_a_znaki_równości">Dwukropki a znaki równości</h3> + +<p>Ten kod nie zadziała prawidłowo, ponieważ nie możesz w ten sposób używać znaków równości, aby korzystać z inicjalizatora objektu.</p> + +<pre class="brush: js example-bad">var obj = { własnośćKlucza = 'wartość' }; +// <span class="short_text" id="result_box" lang="pl"><span>Błąd składni: brakująca własność po identyfikatorze.</span></span> +</pre> + +<p>Poprawnie byłoby użyć znaku dwukropka, lub używając nawiasów kwadratowych aby przydzielić nową własność po stworzeniu objektu</p> + +<pre class="brush: js example-good">var obj = { własnośćKlucza: 'wartość' }; + +// Lub inaczej + +var obj = { }; +obj['własnośćKlucza'] = 'wartość'; +</pre> + +<h3 id="Puste_własności">Puste własności</h3> + +<p>Nie możesz w ten sposób tworzyć pustych własności.</p> + +<pre class="brush: js example-bad">var obj = { własnośćKlucza; }; +// <span class="short_text" id="result_box" lang="pl"><span>Błąd składni: brakująca własność po identyfikatorze.</span></span> +</pre> + +<p>Jeżeli potrzebujesz zdefiniować własność bez wartości, powinieneś użyć {{jsxref("null")}} jako wartości</p> + +<pre class="brush: js example-good">var obj = { własnośćKlucza: null };</pre> + +<h3 id="Własności_obliczeniowe">Własności obliczeniowe</h3> + +<p>Jeżeli tworzysz własność klucza z wyrażenia, potrzebujesz uzyć kwadratowych nawiasów. W przeciwnym razie, nazwa własności nie będzie możliwa do obliczenia</p> + +<pre class="brush: js example-bad">var obj = { 'b'+'ar': 'foo' }; +// <span class="short_text" id="result_box" lang="pl"><span>Błąd składni: brakująca własność po identyfikatorze.</span></span> +</pre> + +<p>Przenieś to wyrażenie do nawiasów <code>[]</code>:</p> + +<pre class="brush: js example-good">var obj = { ['b'+'ar']: 'foo' };</pre> + +<h2 id="Zobacz_również">Zobacz również</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">Inicjalizator objektu</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/index.html b/files/pl/web/javascript/reference/errors/index.html new file mode 100644 index 0000000000..68d78ee3e9 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/index.html @@ -0,0 +1,28 @@ +--- +title: JavaScript error reference +slug: Web/JavaScript/Reference/Errors +tags: + - Błąd + - Błąd javascript + - Debugowanie JavaScript + - JavaScript + - Pomoc JavaScript +translation_of: Web/JavaScript/Reference/Errors +--- +<p>{{jsSidebar("Errors")}}</p> + +<p>Poniżej znajduje się lista błędów JavaScript wyświetlanych w konsoli. Takie błędy mogą być dla Ciebie pomocne w debugowaniu skryptu, natomiast wyświetlany komunikat dotyczący danego błędu nie zawsze jest zrozumiały. Poniższe odnośniki przekierowują Cię na strony, których zawartość szczegółowo opisuje dany problem. Każdy błąd jest traktowany jako obiekt {{jsxref("Error")}}, posiada <code>name</code> oraz <code>message</code>.</p> + +<p>Błędy wyświetlane w konsoli www mogą zawierać łącza do odpowiedniej strony poniżej, aby pomóc Ci szybko zrozumieć problem, który pojawił się w kodzie. </p> + +<h2 id="Lista_błędów">Lista błędów</h2> + +<p>Na tej liście każda strona jest wyświetlana według nazwy (typu błędu) i wiadomości (bardziej czytelna forma błędu dla człowieka w formie komuniaktu). Razem te dwa elementy stanowią punkt wyjścia do zrozumienia problemu. Aby uzyskać więcej informacji, kliknij jeden z poniższych odnośników.</p> + +<p>{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Learn/JavaScript/First_steps/What_went_wrong">What went wrong? Troubleshooting JavaScript</a>: Tutorial dla początkujących - jak naprawić błąd JavaScript.</li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/invalid_array_length/index.html b/files/pl/web/javascript/reference/errors/invalid_array_length/index.html new file mode 100644 index 0000000000..e84d0f36a2 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/invalid_array_length/index.html @@ -0,0 +1,79 @@ +--- +title: 'RangeError: invalid array length' +slug: Web/JavaScript/Reference/Errors/Invalid_array_length +tags: + - Błędy + - Errors + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_array_length +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox">RangeError: Array length must be a finite positive integer (Edge) +RangeError: invalid array length (Firefox) +RangeError: Invalid array length (Chrome) +RangeError: Invalid array buffer length (Chrome) +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Niewłaściwa długość tablicy może wystąpić w następujących sytuacjach:</p> + +<ul> + <li>Kiedy obiekt {{jsxref("Array")}} lub {{jsxref("ArrayBuffer")}} ma długość ujemną albo większą lub równą 2<sup>32</sup>,</li> + <li>przy ustawianiu własności {{jsxref("Array.length")}} na wartość ujemną albo większą lub równą 2<sup>32</sup>.</li> +</ul> + +<p>Dlaczego długość obiektów typu <code>Array</code> i <code>ArrayBuffer</code> jest ograniczona? Własności te są reprezentowane jako 32-bitowe liczby całkowite bez znaku, które mogą przyjmować wartości z zakresu od 0 do 2<sup>32</sup>-1.</p> + +<p>Kiedy tworzysz obiekt typu <code>Array</code>, używając konstruktora, prawdopodobnie chcesz użyć zamiast tego literalnej notacji, gdyż pierwszy argument jest interpretowany jako długość obiektu <code>Array</code>.</p> + +<p><span class="tlid-translation translation" lang="pl"><span title="">W przeciwnym razie możesz chcieć ustalić długość przed ustawieniem właściwości <code>length</code> lub użyć jej jako argumentu konstruktora.</span></span></p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Niepoprawne_przypadki">Niepoprawne przypadki</h3> + +<pre class="brush: js example-bad">new Array(Math.pow(2, 40)) +new Array(-1) +new ArrayBuffer(Math.pow(2, 32)) +new ArrayBuffer(-1) + +let a = []; +a.length = a.length - 1; // ustaw -1 dla własności length + +let b = new Array(Math.pow(2, 32) - 1); +b.length = b.length + 1; // ustaw 2^32 dla własności length +</pre> + +<h3 id="Poprawne">Poprawne</h3> + +<pre class="brush: js example-good">[ Math.pow(2, 40) ] // [ 1099511627776 ] +[ -1 ] // [ -1 ] +new ArrayBuffer(Math.pow(2, 32) - 1) +new ArrayBuffer(0) + +let a = []; +a.length = Math.max(0, a.length - 1); + +let b = new Array(Math.pow(2, 32) - 1); +b.length = Math.min(0xffffffff, b.length + 1); + +// 0xffffffff jest szesnastkowym zapisem dla 2^32 - 1, +// co może być także zapisane jako (-1 >>> 0) +</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li>{{jsxref("Array")}}</li> + <li>{{jsxref("Array.length")}}</li> + <li>{{jsxref("ArrayBuffer")}}</li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/invalid_date/index.html b/files/pl/web/javascript/reference/errors/invalid_date/index.html new file mode 100644 index 0000000000..fe5d685894 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/invalid_date/index.html @@ -0,0 +1,59 @@ +--- +title: 'RangeError: invalid date' +slug: Web/JavaScript/Reference/Errors/Invalid_date +tags: + - Błąd + - Error + - JavaScript + - RangeError +translation_of: Web/JavaScript/Reference/Errors/Invalid_date +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>Wyjątek JavaScript „invalid date” (<em>niewłaściwa data</em>) zdarza się, gdy ciąg znaków zawierający niepoprawną datę jest przekazany do {{jsxref("Date")}} lub {{jsxref("Date.parse()")}}.</p> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox notranslate">RangeError: invalid date (Edge) +RangeError: invalid date (Firefox) +RangeError: invalid time value (Chrome) +RangeError: Provided date is not in valid range (Chrome) +</pre> + +<h2 id="Rodzaj_błędu">Rodzaj błędu</h2> + +<p>{{jsxref("RangeError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Ciąg znaków przekazany do {{jsxref("Date")}} lub {{jsxref("Date.parse()")}} prowadzi do niepoprawnej daty.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Niepoprawne_przypadki">Niepoprawne przypadki</h3> + +<p>Ciągi znaków, w których nie można rozpoznać daty, lub które zawierają elementy niezgodne ze standardem ISO w większości przypadków spowodują zwrócenie {{jsxref("NaN")}}. Jednakże — w zależności od implementacji — niektóre wartości niezgodne z formatem ISO mogą także spowodować błąd <code>RangeError: invalid date</code>, tak jak następujące przypadki w przeglądarce Firefox:</p> + +<pre class="brush: js example-bad notranslate">new Date('foo-bar 2014'); +new Date('2014-25-23').toISOString(); +new Date('foo-bar 2014').toString(); +</pre> + +<p>Jednocześnie poniższy przykład zwróci w Firefoksie wartość {{jsxref("NaN")}}:</p> + +<pre class="brush: js example-bad notranslate">Date.parse('foo-bar 2014'); // NaN</pre> + +<p>Więcej szczegółów znajduje się w dokumentacji {{jsxref("Date.parse()")}}.</p> + +<h3 id="Poprawne_przypadki">Poprawne przypadki</h3> + +<pre class="brush: js example-good notranslate">new Date('05 October 2011 14:48 UTC'); +new Date(1317826080); // Timestamp Unix dla daty 5 października 2011 14:48:00 UTC</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li>{{jsxref("Date")}}</li> + <li>{{jsxref("Date.prototype.parse()")}}</li> + <li>{{jsxref("Date.prototype.toISOString()")}}</li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/json_bad_parse/index.html b/files/pl/web/javascript/reference/errors/json_bad_parse/index.html new file mode 100644 index 0000000000..a57c961088 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/json_bad_parse/index.html @@ -0,0 +1,114 @@ +--- +title: 'SyntaxError: JSON.parse: bad parsing' +slug: Web/JavaScript/Reference/Errors/JSON_bad_parse +tags: + - Błąd składniowy + - Błędy + - Errors + - JSON + - JavaScript + - Metodă + - SyntaxError + - Własność +translation_of: Web/JavaScript/Reference/Errors/JSON_bad_parse +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomosć">Wiadomosć</h2> + +<pre class="syntaxbox">SyntaxError: JSON.parse: unterminated string literal +SyntaxError: JSON.parse: bad control character in string literal +SyntaxError: JSON.parse: bad character in string literal +SyntaxError: JSON.parse: bad Unicode escape +SyntaxError: JSON.parse: bad escape character +SyntaxError: JSON.parse: unterminated string +SyntaxError: JSON.parse: no number after minus sign +SyntaxError: JSON.parse: unexpected non-digit +SyntaxError: JSON.parse: missing digits after decimal point +SyntaxError: JSON.parse: unterminated fractional number +SyntaxError: JSON.parse: missing digits after exponent indicator +SyntaxError: JSON.parse: missing digits after exponent sign +SyntaxError: JSON.parse: exponent part is missing a number +SyntaxError: JSON.parse: unexpected end of data +SyntaxError: JSON.parse: unexpected keyword +SyntaxError: JSON.parse: unexpected character +SyntaxError: JSON.parse: end of data while reading object contents +SyntaxError: JSON.parse: expected property name or '}' +SyntaxError: JSON.parse: end of data when ',' or ']' was expected +SyntaxError: JSON.parse: expected ',' or ']' after array element +SyntaxError: JSON.parse: end of data when property name was expected +SyntaxError: JSON.parse: expected double-quoted property name +SyntaxError: JSON.parse: end of data after property name when ':' was expected +SyntaxError: JSON.parse: expected ':' after property name in object +SyntaxError: JSON.parse: end of data after property value in object +SyntaxError: JSON.parse: expected ',' or '}' after property value in object +SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal +SyntaxError: JSON.parse: property names must be double-quoted strings +SyntaxError: JSON.parse: expected property name or '}' +SyntaxError: JSON.parse: unexpected character +SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data +SyntaxError: JSON.parse Error: Invalid character at position {0} (Edge)</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>{{jsxref("JSON.parse()")}} parsuje string jako JSON. Zadany string musi być poprawnym dokumentem JSON, więc błąd wystąpi wtedy, gdy zostanie napotkana niepoprawna składnia.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="JSON.parse_nie_pozwala_na_końcowe_przecinki"><code>JSON.parse()</code> nie pozwala na końcowe przecinki</h3> + +<p>Both lines will throw a SyntaxError:</p> + +<pre class="brush: js example-bad">JSON.parse('[1, 2, 3, 4,]'); +JSON.parse('{"foo": 1,}'); +// SyntaxError JSON.parse: unexpected character +// at line 1 column 14 of the JSON data +</pre> + +<p>Pomiń końcowe przecinki, aby sparsować dokument JSON w poprawny sposób:</p> + +<pre class="brush: js example-good">JSON.parse('[1, 2, 3, 4]'); +JSON.parse('{"foo": 1}');</pre> + +<h3 id="Nazwy_własności_muszą_znajdować_się_w_cudzysłowach">Nazwy własności muszą znajdować się w cudzysłowach</h3> + +<p>Nie możesz użyć apostrofów do określania nazw własności, jak np. 'foo'.</p> + +<pre class="brush: js example-bad">JSON.parse("{'foo': 1}"); +// SyntaxError: JSON.parse: expected property name or '}' +// at line 1 column 2 of the JSON data</pre> + +<p>Zamiast tego użyj "foo":</p> + +<pre class="brush: js example-good">JSON.parse('{"foo": 1}');</pre> + +<h3 id="Zera_wiodące_i_część_niecałkowita_liczby">Zera wiodące i część niecałkowita liczby</h3> + +<p>Nie możesz użyć zer wiodących, jak na przykład <code>01</code>, ponadto część niecałkowita musi zawierać co najmniej jedną cyfrę, jeśli używany jest format dziesiętny.</p> + +<pre class="brush: js example-bad">JSON.parse('{"foo": 01}'); +// SyntaxError: JSON.parse: expected ',' or '}' after property value +// in object at line 1 column 2 of the JSON data + +JSON.parse('{"foo": 1.}'); +// SyntaxError: JSON.parse: unterminated fractional number +// at line 1 column 2 of the JSON data +</pre> + +<p>Zamiast tego napisz po prostu <code>1</code> bez zera z przodu i użyj co najmniej jednej cyfry w częsci dziesiętnej:</p> + +<pre class="brush: js example-good">JSON.parse('{"foo": 1}'); +JSON.parse('{"foo": 1.0}'); +</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li>{{jsxref("JSON")}}</li> + <li>{{jsxref("JSON.parse()")}}</li> + <li>{{jsxref("JSON.stringify()")}}</li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/missing_curly_after_function_body/index.html b/files/pl/web/javascript/reference/errors/missing_curly_after_function_body/index.html new file mode 100644 index 0000000000..efabf665c9 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/missing_curly_after_function_body/index.html @@ -0,0 +1,72 @@ +--- +title: 'SyntaxError: missing } after function body' +slug: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +tags: + - Błąd + - Błąd składni + - Błędy + - Error + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>Wyjątek JavaScript "missing } after function body" (<em>brakujący } po ciele funkcji</em>) zdarza się, gdy jest błąd składniowy gdzieś w definicji funkcji. Należy sprawdzić, czy wszystkie klamry i nawiasy są w odpowiednich miejscach i kolejności.</p> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox notranslate">SyntaxError: Expected '}' (Edge) +SyntaxError: missing } after function body (Firefox) +</pre> + +<h2 id="Rodzaj_błędu">Rodzaj błędu</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>W którymś miejscu pojawił się błąd przy tworzeniu funkcji. Należy sprawdzić, czy wszystkie zamykaące klamry i nawiasy są we właściwej kolejności. Odpowiednie wcięcia i formatowanie kodu mogą pomóc Ci w odnalezieniu błędu.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Brakująca_klamra_zamykająca">Brakująca klamra zamykająca</h3> + +<p>Często zdarza się, że brakuje klamry zamykającej w funkcji w Twoim kodzie:</p> + +<pre class="brush: js example-bad notranslate">var charge = function() { + if (sunny) { + useSolarCells(); + } else { + promptBikeRide(); +}; +</pre> + +<p>Poprawny kod wygląda następująco:</p> + +<pre class="brush: js example-good notranslate">var charge = function() { + if (sunny) { + useSolarCells(); + } else { + promptBikeRide(); + } +};</pre> + +<p>Może to być o wiele bardziej niejasne, kiedy używane są <a href="/en-US/docs/Glossary/IIFE">IIFE</a>, <a href="/pl/docs/Web/JavaScript/Domkniecia">domknięcia</a>, czy inne konstrukcje wymagające wielu różnych nawiasów i klamer, jak na przykład:</p> + +<pre class="brush: js example-bad notranslate">(function() { if (true) { return false; } ); +</pre> + +<p>Często zastosowanie innych wcięć lub dokładne sprawdzenie poprawności wcięć pozwala na znalezienie błędów tego rodzaju.</p> + +<pre class="brush: js example-good notranslate">(function() { + if (true) { + return false; + } +});</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/pl/docs/Web/JavaScript/Guide/Funkcje">Funkcje</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/missing_initializer_in_const/index.html b/files/pl/web/javascript/reference/errors/missing_initializer_in_const/index.html new file mode 100644 index 0000000000..457a8e6a97 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/missing_initializer_in_const/index.html @@ -0,0 +1,61 @@ +--- +title: 'SyntaxError: missing = in const declaration' +slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +tags: + - Błąd + - Błąd składni + - Error + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_initializer_in_const +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox">SyntaxError: Const must be initalized (Edge) +SyntaxError: missing = in const declaration (Firefox) +SyntaxError: Missing initializer in const declaration (Chrome) +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("SyntaxError")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Stała jest wartością, która nie może być zmieniona podczas normalnego wykonania programu. Nie może być zmodyfikowana poprzez ponowne przypisanie wartości ani ponowną deklarację. W języku JavaScipt, stałe są deklarowane za pomocą słowa kluczowego <code>const</code>. Wymagane jest zainicjowanie stałej konkretną wartością – konieczne jest przypisanie danej stałej wartości w tym samym wyrażeniu, w którym jest deklarowana (co ma sens, biorąc pod uwagę fakt, że nie może ona być później zmieniana).</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Brakująca_inicjalizacja_stałej">Brakująca inicjalizacja stałej</h3> + +<p>W przeciwieństwie do <code>var</code> lub <code>let</code>, konieczne jest podanie wartości przy deklaracji <code>const</code>. W przeciwnym razie zwracany jest błąd:</p> + +<pre class="brush: js example-bad">const COLUMNS; +// SyntaxError: missing = in const declaration</pre> + +<h3 id="Naprawianie_błędu">Naprawianie błędu</h3> + +<p>Jest wiele opcji, by naprawić ten błąd. Należy sprawdzić, czemu miała służyć stała, o której mowa.</p> + +<h4 id="Dodawanie_wartości_stałej">Dodawanie wartości stałej</h4> + +<p>Ustal wartość stałej w tym samym wyrażeniu, w którym jest ona deklarowana:</p> + +<pre class="brush: js example-good">const COLUMNS = 80;</pre> + +<h4 id="const_let_or_var"><code>const</code>, <code>let</code> or <code>var</code>?</h4> + +<p>Nie używaj <code>const</code> tam, gdzie nie chcesz użyć stałej. Być może chciałeś zadeklarować zmienną z zakresem ograniczonym do danego bloku kodu za pomocą <code>let</code> lub zmienną globalną przy użyciu <code>var</code>. Obydwie te opcje nie wymagają wartości początkowej.</p> + +<pre class="brush: js example-good">let columns; +</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/const">const</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/let">let</a></code></li> + <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/var">var</a></code></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html b/files/pl/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html new file mode 100644 index 0000000000..a821081889 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.html @@ -0,0 +1,59 @@ +--- +title: 'SyntaxError: missing ) after argument list' +slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +tags: + - Błąd + - Błąd składni + - Błędy + - Error + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>Wyjątek JavaScript „missing ) after argument list” (brakujący „)” po liście argumentów) występuje, gdy pojawia się błąd przy próbie wywołania funkcji. Może być on spowodowany literówką, brakującym operatorem lubciągiem znaków, w którym nie został zastosowany znak ucieczki tam, gdzie był potrzebny.</p> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox notranslate">SyntaxError: Expected ')' (Edge) +SyntaxError: missing ) after argument list (Firefox) +</pre> + +<h2 id="Rodzaj_błędu">Rodzaj błędu</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Wystąpił błąd w wywołaniu funkcji. Powodem może być na przykład literówka, brakujący operator lub brak znaku ucieczki w ciągu znaków, gdy zastosowanie go było potrzebne.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<p>Ponieważ brakuje operatora <code>+</code> przy próbie połączenia ciągów znaków, JavaScript oczekuje, że jedynym argumentem funkcji <code>log</code> będzie <code>"PI: "</code>, a zatem że nastąpi po nim nawias zamykający.</p> + +<pre class="brush: js example-bad notranslate">console.log('PI: ' Math.PI); +// SyntaxError: missing ) after argument list +</pre> + +<p>Można naprawić wywołanie funkcji <code>log</code> poprzez dodanie brakującego operatora <code>+</code>:</p> + +<pre class="brush: js example-good notranslate">console.log('PI: ' + Math.PI); +// "PI: 3.141592653589793"</pre> + +<h3 id="Niedokończone_ciągi_znaków">Niedokończone ciągi znaków</h3> + +<pre class="brush: js example-bad notranslate">console.log('"Java" + "Script" = \"' + 'Java' + 'Script\"); +// SyntaxError: missing ) after argument list</pre> + +<p>W powyższym przypadku JavaScript sądzi, że chciałeś użyć <code>);</code> jako fragmentu ciągu znaków (<em>string</em>) i ignoruje to, ponieważ nie wie, że <code>);</code> miało zakończyć wywołanie funkcji <code>console.log</code>. Aby naprawić ten problem, należy dodać znak <code>'</code> na końcu ciągu znaków, po fragmencie <code>'Script\"</code>:</p> + +<pre class="brush: js example-good notranslate">console.log('"Java" + "Script" = \"' + 'Java' + 'Script\"'); +// '"Java" + "Script" = "JavaScript"' +</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/pl/docs/Web/JavaScript/Guide/Funkcje">Funkcje</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/pl/web/javascript/reference/errors/missing_semicolon_before_statement/index.html new file mode 100644 index 0000000000..6ff362a7aa --- /dev/null +++ b/files/pl/web/javascript/reference/errors/missing_semicolon_before_statement/index.html @@ -0,0 +1,82 @@ +--- +title: zezwalaj na wklejanie +slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +tags: + - Errors + - JavaScript + - SyntaxError +translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox">SyntaxError: Expected ';' (Edge) +SyntaxError: missing ; before statement (Firefox) +</pre> + +<h2 id="Typ_Błędu">Typ Błędu</h2> + +<p>{{jsxref("SyntaxError")}}.</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Brakuje gdzieś średnika (;). Instrukcje JavaScript muszą być zakończone średnikami. Niektóre z nich podlegają automatycznemu wstawianiu średnika (ASI), ale w tym przypadku musisz podać średnik, aby JavaScript mógł poprawnie przeanalizować kod źródłowy.</p> + +<p>Jednak często ten błąd jest tylko konsekwencją innego błędu, takiego jak niewłaściwe unikanie ciągów znaków lub niewłaściwe używanie zmiennej var. Możesz także mieć gdzieś za dużo nawiasów. Dokładnie sprawdź składnię, gdy ten błąd zostanie zgłoszony.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Niezdefiniowane_wiersze">Niezdefiniowane wiersze</h3> + +<p>Ten błąd może wystąpić z łatwością, gdy łańcuch znaków nie jest poprawnie zlozony, a silnik JavaScript oczekuje już końca łańcucha. Na przykład:</p> + +<pre class="brush: js example-bad">var foo = 'Tom's bar'; +// SyntaxError: missing ; before statement</pre> + +<p>Możesz użyć podwójnych cudzysłowów lub uciec od apostrofu:</p> + +<pre class="brush: js example-good">var foo = "Tom's bar"; +var foo = 'Tom\'s bar'; +</pre> + +<h3 id="Deklarowanie_właściwości_za_pomocą_var">Deklarowanie właściwości za pomocą var</h3> + +<p>Nie można zadeklarować właściwości obiektu lub tablicy za pomocą deklaracji var.</p> + +<pre class="brush: js example-bad">var obj = {}; +var obj.foo = 'hi'; // SyntaxError missing ; before statement + +var array = []; +var array[0] = 'there'; // SyntaxError missing ; before statement +</pre> + +<p>Zamiast tego pomiń słowo kluczowe var:</p> + +<pre class="brush: js example-good">var obj = {}; +obj.foo = 'hi'; + +var array = []; +array[0] = 'there'; +</pre> + +<h3 id="Bad_keywords">Bad keywords</h3> + +<p>Jeśli pochodzisz z innego języka programowania, często używasz słów kluczowych, które nie oznaczają tego samego lub nie mają żadnego znaczenia w javaScript:</p> + +<pre class="brush: js example-bad">def print(info){ + console.log(info); +}; // SyntaxError missing ; before statement</pre> + +<p>Zamiast tego użyj funkcji def:</p> + +<pre class="brush: js example-good">function print(info){ + console.log(info); +};</pre> + +<h2 id="Zobacz_tez">Zobacz tez</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">Automatic semicolon insertion (ASI)</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statements</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/more_arguments_needed/index.html b/files/pl/web/javascript/reference/errors/more_arguments_needed/index.html new file mode 100644 index 0000000000..309031c6d0 --- /dev/null +++ b/files/pl/web/javascript/reference/errors/more_arguments_needed/index.html @@ -0,0 +1,44 @@ +--- +title: 'TypeError: More arguments needed' +slug: Web/JavaScript/Reference/Errors/More_arguments_needed +translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Komunikat">Komunikat</h2> + +<pre class="syntaxbox">TypeError: Object.create requires more than 0 arguments +TypeError: Object.setPrototypeOf requires more than 1 argument +TypeError: Object.defineProperties requires more than 0 arguments +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Błąd zaistniał w sposobie wywołania funkcji. Należy podać więcej argumentów.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<p>Metoda {{jsxref("Object.create()")}} wymaga przynajmniej jednego argumentu a metoda {{jsxref("Object.setPrototypeOf()")}} wymaga przynajmniej dwóch:</p> + +<pre class="brush: js example-bad">var obj = Object.create(); +// TypeError: Object.create requires more than 0 arguments + +var obj = Object.setPrototypeOf({}); +// TypeError: Object.setPrototypeOf requires more than 1 argument +</pre> + +<p>Możesz temu zaradzić ustawiając {{jsxref("null")}} jako prototyp, na przykład:</p> + +<pre class="brush: js example-good">var obj = Object.create(null); + +var obj = Object.setPrototypeOf({}, null);</pre> + +<h2 id="Zobacz_również">Zobacz również</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions">Functions</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/not_a_function/index.html b/files/pl/web/javascript/reference/errors/not_a_function/index.html new file mode 100644 index 0000000000..019a223f0f --- /dev/null +++ b/files/pl/web/javascript/reference/errors/not_a_function/index.html @@ -0,0 +1,84 @@ +--- +title: 'TypeError: "x" nie jest funkcją' +slug: Web/JavaScript/Reference/Errors/Not_a_function +tags: + - Errors + - JavaScript + - TypeError +translation_of: Web/JavaScript/Reference/Errors/Not_a_function +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox">TypeError: "x" is not a function +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="Co_poszło_źle">Co poszło źle?</h2> + +<p>Próbowano wywołać wartość jak funkcję, ale wartość nie jest funkcją. Kod oczekuje od Ciebie przekazania funkcji, co nie miało miejsca.</p> + +<p>Może zrobiłeś literówkę w nazwie funkcji? Może objekt na którym wywołujesz tę metodę nie posiada tej funkcji? Na przykład, objekt JavaScript nie posiada funkcji <em>map, </em>natomiast objekt JavaScript Array posiada.</p> + +<p>Istnieje mnóstwo wbudowanych funkcji wymagających (callback) funkcji. Będziesz musiał wprowadzić funkcję, by metody te działały poprawnie:</p> + +<ul> + <li>Gdy pracujesz z {{jsxref("Array")}} lub {{jsxref("TypedArray")}} objektami: + <ul> + <li>{{jsxref("Array.prototype.every()")}}, {{jsxref("Array.prototype.some()")}}, {{jsxref("Array.prototype.forEach()")}}, {{jsxref("Array.prototype.map()")}}, {{jsxref("Array.prototype.filter()")}}, {{jsxref("Array.prototype.reduce()")}}, {{jsxref("Array.prototype.reduceRight()")}}, {{jsxref("Array.prototype.find()")}}</li> + </ul> + </li> + <li>Gdy pracujesz z {{jsxref("Map")}} i {{jsxref("Set")}} objektami: + <ul> + <li>{{jsxref("Map.prototype.forEach()")}} and {{jsxref("Set.prototype.forEach()")}}</li> + </ul> + </li> +</ul> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Literówka_w_nazwie_funkcji">Literówka w nazwie funkcji</h3> + +<p>W tym wypadku, co zdarza się zbyt często, jest literówka w nazwie metody:</p> + +<pre class="brush: js example-bad">var x = document.getElementByID('foo'); +// TypeError: document.getElementByID is not a function +</pre> + +<p>Poprawna naywa metody to <code>getElementByI<strong>d</strong></code>:</p> + +<pre class="brush: js example-good">var x = document.getElementById('foo'); +</pre> + +<h3 id="Funkcje_wywołane_na_nieodpowiednim_objekcie">Funkcje wywołane na nieodpowiednim objekcie</h3> + +<p>Dla pewnych metod, musisz podać (callback) funkcję, która będzie działała tylko dla specyficznych objektów. W tym przykładzie, {{jsxref("Array.prototype.map()")}} jest użyta, podczas gdy działa tylko z objektami {{jsxref("Array")}}</p> + +<pre class="brush: js example-bad">var obj = {a: 13, b: 37, c: 42}; + +obj.map(function(num) { + return num * 2; +}); + +// TypeError: obj.map is not a function</pre> + +<p>Użyj w zamian <em>array:</em></p> + +<pre class="brush: js example-good">var numbers = [1, 4, 9]; + +numbers.map(function(num) { + return num * 2; +}); + +// Array [2, 8, 18] +</pre> + +<h2 id="Zobacz_również">Zobacz również</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions">Functions</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/not_defined/index.html b/files/pl/web/javascript/reference/errors/not_defined/index.html new file mode 100644 index 0000000000..a5e72f84cb --- /dev/null +++ b/files/pl/web/javascript/reference/errors/not_defined/index.html @@ -0,0 +1,66 @@ +--- +title: 'ReferenceError: "x" is not defined' +slug: Web/JavaScript/Reference/Errors/Not_defined +translation_of: Web/JavaScript/Reference/Errors/Not_defined +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox">ReferenceError: "x" is not defined +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("ReferenceError")}}.</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Istnieje gdzieś niezadeklarowana zmienna. Zmienna ta powinna być zadeklarowana, a jeśli jest upewnij się czy jest dostępna w twoim skrypcie albo {{Glossary("scope")}}.</p> + +<div class="note"> +<p><strong>Notatka:</strong> Gdy ładujesz bibliotekę (na przykład jQuery), <span id="result_box" lang="pl"><span>upewnij się, że jest załadowana przed dostępem do zmiennych biblioteki, np</span></span> "$". Dodaj znacznik {{HTMLElement("script")}} ładujący bibliotekę przed twoim kodem, który jej używa.</p> +</div> + +<h2 id="Przykład">Przykład</h2> + +<h3 id="Zmienna_niezadeklarowana">Zmienna niezadeklarowana</h3> + +<pre class="brush: js example-bad">foo.substring(1); // ReferenceError: foo is not defined +</pre> + +<p>Zmianna "foo" jest niezdefiniowana. Powinna być jakąś wartością string wiec("String.prototype.substring()")}} metoda ta będzie działać.</p> + +<pre class="brush: js example-good">var foo = 'bar'; +foo.substring(1); // "ar"</pre> + +<h3 id="Zły_zasięg">Zły zasięg</h3> + +<p><span id="result_box" lang="pl"><span>Zmienna musi być dostępna w bieżącym kontekście realizacji.</span> <span>Zmienne zdefiniowane wewnątrz</span></span> <a href="/en-US/docs/Web/JavaScript/Reference/Functions">funcji </a><span lang="pl"><span>nie mogą być dostępne z dowolnego miejsca poza funkcją, powodem jest to że zmienna jest zdefiniowana tylko zmienną lokalną funkcji.</span></span></p> + +<pre class="brush: js example-bad">function numbers() { + var num1 = 2, + num2 = 3; + return num1 + num2; +} + +console.log(num1); // ReferenceError num1 is not defined.</pre> + +<p>Jakkolwiek funkcja może mieć dostęp do wszystkich zmiennych dzięki deklaracji zmiennych globalnie. Zmienne globalne są dostępne dla wszystkich funkcji.</p> + +<pre class="brush: js example-good">var num1 = 2, + num2 = 3; + +function numbers() { + return num1 + num2; +} + +console.log(num1); // 2</pre> + +<h2 id="Zobacz_także">Zobacz także</h2> + +<ul> + <li>{{Glossary("Scope")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declaring_variables">Przewodnik deklaracji zmiennych w JavaScript</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Functions#Function_scope/en-US/docs/">Zasięg funkcji w Javascript</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/property_access_denied/index.html b/files/pl/web/javascript/reference/errors/property_access_denied/index.html new file mode 100644 index 0000000000..5db1ef3cad --- /dev/null +++ b/files/pl/web/javascript/reference/errors/property_access_denied/index.html @@ -0,0 +1,53 @@ +--- +title: 'Error: Permission denied to access property "x"' +slug: Web/JavaScript/Reference/Errors/Property_access_denied +tags: + - Bezpieczeństwo + - Błąd + - Błędy + - Error + - Errors + - JavaScript +translation_of: Web/JavaScript/Reference/Errors/Property_access_denied +--- +<div>{{jsSidebar("Errors")}}</div> + +<p>Wyjątek JavaScript "Permission denied to access property" pojawia się podczas próby dostępu do obiektu, do którego nie masz uprawnień</p> + +<h2 id="Wiadomość">Wiadomość</h2> + +<pre class="syntaxbox notranslate">Error: Permission denied to access property "x" +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("Error")}}</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Podjęto próbę dostępu do obiektu, do którego nie masz uprawnień. There was attempt to access an object for which you have no permission.Jest to prawdopodobnie element <a href="/en-US/docs/Web/HTML/Element/iframe" title="The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one."><code><iframe></code></a> załadowany z innej domeny, dla której naruszyłeś <a href="/en-US/docs/Web/Security/Same-origin_policy">regułę tego samego pochodzenia (same-origin policy)</a>.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Brak_uprawnień_dostepu_do_dokumentu">Brak uprawnień dostepu do dokumentu</h3> + +<pre class="brush: html notranslate"><!DOCTYPE html> +<html> + <head> + <iframe id="myframe" src="http://www1.w3c-test.org/common/blank.html"></iframe> + <script> + onload = function() { + console.log(frames[0].document); + // Error: Permission denied to access property "document" + } + </script> + </head> + <body></body> +</html></pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Web/HTML/Element/iframe" title="The HTML Inline Frame element (<iframe>) represents a nested browsing context, embedding another HTML page into the current one."><code><iframe></code></a></li> + <li><a href="/pl/docs/Web/Bezpieczeństwo/Same-origin_policy">Reguła tego samego pochodzenia (same-origin policy)</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/errors/unexpected_type/index.html b/files/pl/web/javascript/reference/errors/unexpected_type/index.html new file mode 100644 index 0000000000..39b363d42f --- /dev/null +++ b/files/pl/web/javascript/reference/errors/unexpected_type/index.html @@ -0,0 +1,69 @@ +--- +title: 'TypeError: "x" is (not) "y"' +slug: Web/JavaScript/Reference/Errors/Unexpected_type +tags: + - Błąd TypeError + - Błąd undefined + - Wartość null +translation_of: Web/JavaScript/Reference/Errors/Unexpected_type +--- +<div>{{jsSidebar("Errors")}}</div> + +<h2 id="Message">Message</h2> + +<pre class="syntaxbox">TypeError: "x" is (not) "y" + +Examples: +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 +</pre> + +<h2 id="Typ_błędu">Typ błędu</h2> + +<p>{{jsxref("TypeError")}}.</p> + +<h2 id="Co_poszło_nie_tak">Co poszło nie tak?</h2> + +<p>Pojawił się nieoczekiwany typ, dlatego pojawił się błąd. Błąd pojawia się często jako {{jsxref("undefined")}} albo {{jsxref("null")}} dla określonych wartości.</p> + +<p>Dodatkowo niektóre metody takie jak {{jsxref("Object.create()")}} albo {{jsxref("Symbol.keyFor()")}}, wymagają określonego typu, który musi być zadeklarowany.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Nieprawidłowe_przypadki_które_mogą_się_pojawić">Nieprawidłowe przypadki, które mogą się pojawić</h3> + +<pre class="brush: js example-bad">// undefined oraz null to przypadki, dla których pojawi się błąd +var foo = undefined; +foo.substring(1); // TypeError: foo is undefined + +var foo = null; +foo.substring(1); // TypeError: foo is null + + +// <span class="short_text" id="result_box" lang="pl"><span>Niektóre metody mogą wymagać określonego typu</span></span> +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 +</pre> + +<h2 id="Jak_naprawić">Jak naprawić?</h2> + +<p>Aby naprawić problem, w przypadku wyświetlenia <code>'undefined'</code> bądź '<code>null</code>' dla określonych wartości można użyć operatora <a href="/en-US/docs/Web/JavaScript/Reference/Operators/typeof">typeof.</a></p> + +<h3 id="Przykład">Przykład</h3> + +<pre class="brush: js">if (typeof foo !== 'undefined') { + // Teraz wiemy, że zmienna foo jest zdefiniowana +}</pre> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li>{{jsxref("undefined")}}</li> + <li>{{jsxref("null")}}</li> +</ul> diff --git a/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html b/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html new file mode 100644 index 0000000000..d1b9d6010f --- /dev/null +++ b/files/pl/web/javascript/reference/functions/funkcje_strzalkowe/index.html @@ -0,0 +1,355 @@ +--- +title: Funkcje strzałkowe +slug: Web/JavaScript/Reference/Functions/Funkcje_strzalkowe +translation_of: Web/JavaScript/Reference/Functions/Arrow_functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><strong>Funkcja strzałkowa </strong>ma krótszą składnię niż <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">zwykłe wyrażenie funkcji</a> oraz nie posiada własnego <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">argumentów</a>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super</a>, tudzież właściwości <a href="/en-US/docs/Web/JavaScript/Reference/Operators/new.target">new.target</a>. Taki sposób wyrażenia funkcji najlepiej wykorzystać przy tworzeniu funkcji bez metod, ponadto nie mogą zostać one użyte jako konstruktory.</p> + +<h2 id="Składnia">Składnia</h2> + +<h3 id="Składnia_podstawowa">Składnia podstawowa</h3> + +<pre class="syntaxbox"><strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) => {</strong> <em>statements</em> <strong>}</strong> +<strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>) =></strong> <em>expression</em> +// inaczej mówiąc: <strong>(</strong><em>param1</em>, <em>param2</em>, …, <em>paramN</em><strong>)</strong> => { return <em>expression</em>; } + +// Nawiasy są opcjonalne jeżeli występuje wyłącznie jedna nazwa parametru: +<em>(singleParam)</em> <strong>=> {</strong> <em>statements</em> <strong>}</strong> +<em>singleParam</em> <strong>=></strong> { <em>statements </em>} +<em>singleParam</em> <strong>=></strong> <em>expression</em> + + +// Lista parametrów dla funkcji bez parametrów powinna być zapisana przy użyciu pustego nawiasu. +() => { <em>statements</em> } +</pre> + +<h3 id="Zaawansowana_składnia">Zaawansowana składnia</h3> + +<pre class="syntaxbox">// Otoczenie ciała funkcji nawiasami pozwoli zwrócić tzw. object literal expression: +<em>params</em> => ({<em>foo: bar</em>}) + +// Parametry Rest (<a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a>) i domyślne (<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a>) są wspierane +(<em>param1</em>, <em>param2</em>, <strong>...rest</strong>) => { <em>statements</em> } +(<em>param1</em> <strong>= defaultValue1</strong>, <em>param2</em>, …, paramN <strong>= defaultValueN</strong>) => { <em>statements</em> } + +// Destrukturyzacja (<a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">Destructuring</a>) w ramach listy parametrów jest również wspierana +let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; +f(); +// 6 +</pre> + +<h2 id="Opis">Opis</h2> + +<p>Zobacz również <a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" na hacks.mozilla.org</a>.</p> + +<p>Dwa czynniki, które wpłynęły na wprowadzenie funkcji strzałkowych: krótszy zapis funkcji i brak wiązania <code>this</code>.</p> + +<h3 id="Krótsze_funkcje">Krótsze funkcje</h3> + +<pre class="brush: js">var materials = [ + 'Hydrogen', + 'Helium', + 'Lithium', + 'Beryllium' +]; + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(function(material) { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>((material) => { + return material.length; +}); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(material => material.length); // [8, 6, 7, 9] + +materials.<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>(({ length }) => length); // [8, 6, 7, 9] +</pre> + +<h3 id="Brak_oddzielnego_this">Brak oddzielnego <code>this</code></h3> + +<p>Przed wprowadzeniem funkcji strzałkowych każda nowa funkcja deniniowała swoją własną wartość <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">this</a></code> (nowy obiekt w przypadku konstruktora, undefined w wywołaniach funkcji <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, obiekt bazowy jeśli funkcja jest wywoływana jako "metoda obiektowa", itp.). Okazało się to niekorzystne przy obiektowym stylu programowania.</p> + +<pre class="brush: js">function Person() { + // Konstruktor Person() definiuje `this` jako instancję samego siebie. + this.age = 0; + + setInterval(function growUp() { + // Bez trybu non-strict, funkcja growUp() definuje `this` + // jako obiekt globalny, który jest inny od `this` + // zdefiniowanego przez konstruktor Person(). + this.age++; + }, 1000); +} + +var p = new Person();</pre> + +<p>W ECMAScript 3/5, problem z <code>this</code> można było rozwiązać przez przydzielenie wartości <code>this</code> do zmiennej, która wygląda bardzo podobnie.</p> + +<pre class="brush: js">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); +}</pre> + +<p>Można było również stworzyć <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">funkcję bound</a>, co pozwoliło nadać wstępnie przypisaną wartość <code>this</code> do powiązanej funkcji docelowej (funkcja <code>growUp()</code> w przykładzie powyżej).</p> + +<p>Funkcja strzałkowa nie posiada własnego <code>this</code>; używana jest wartość <code>this</code> kontekstu wykonania. W związku z tym, w poniższym kodzie, <code>this</code> użyty w funkcji, który jest przekazywany do <code>setInterval</code>, ma taką samą wartość jak <code>this</code> w funkcji otaczającej:</p> + +<pre class="brush: js">function Person(){ + this.age = 0; + + setInterval(() => { + this.age++; // własność |this| właściwie odnosi się do obiektu Person() + }, 1000); +} + +var p = new Person();</pre> + +<h4 id="Relation_with_strict_mode">Relation with strict mode</h4> + +<p>Given that <code>this</code> comes from the surrounding lexical context, <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a> rules with regard to <code>this</code> are ignored.</p> + +<pre class="brush: js">var f = () => { 'use strict'; return this; }; +f() === window; // or the global object</pre> + +<p>All other strict mode rules apply normally.</p> + +<h4 id="Invoked_through_call_or_apply">Invoked through call or apply</h4> + +<p>Since arrow functions do not have their own <code>this</code>, the methods <code>call()</code> or <code>apply()</code> can only pass in parameters. <code>thisArg</code> is ignored.</p> + +<pre class="brush: js">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</pre> + +<h3 id="No_binding_of_arguments">No binding of <code>arguments</code></h3> + +<p>Arrow functions do not have their own <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments"><code>arguments</code> object</a>. Thus, in this example, <code>arguments</code> is simply a reference to the the arguments of the enclosing scope:</p> + +<pre class="brush: js">var arguments = [1, 2, 3]; +var arr = () => arguments[0]; + +arr(); // 1 + +function foo(n) { + var f = () => arguments[0] + n; // <em>foo</em>'s implicit arguments binding. arguments[0] is n + return f(10); +} + +foo(1); // 2</pre> + +<p>In most cases, using <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a> is a good alternative to using an <code>arguments</code> object.</p> + +<pre class="brush: js">function foo(n) { + var f = (...args) => args[0] + n; + return f(10); +} + +foo(1); // 11</pre> + +<h3 id="Arrow_functions_used_as_methods">Arrow functions used as methods</h3> + +<p>As stated previously, arrow function expressions are best suited for non-method functions. Let's see what happens when we try to use them as methods:</p> + +<pre class="brush: js">'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 {...}</pre> + +<p>Arrow functions do not have their own <code>this</code>. Another example involving {{jsxref("Object.defineProperty()")}}:</p> + +<pre class="brush: js">'use strict'; +var obj = { + a: 10 +}; + +Object.defineProperty(obj, 'b', { + get: () => { + console.log(this.a, typeof this.a, this); + return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' + } +}); +</pre> + +<h3 id="Use_of_the_new_operator">Use of the <code>new</code> operator</h3> + +<p>Arrow functions cannot be used as constructors and will throw an error when used with <code>new</code>.</p> + +<pre class="brush: js">var Foo = () => {}; +var foo = new Foo(); // TypeError: Foo is not a constructor</pre> + +<h3 id="Use_of_prototype_property">Use of <code>prototype</code> property</h3> + +<p>Arrow functions do not have a <code>prototype</code> property.</p> + +<pre class="brush: js">var Foo = () => {}; +console.log(Foo.prototype); // undefined +</pre> + +<h3 id="Use_of_the_yield_keyword">Use of the <code>yield</code> keyword</h3> + +<p>The <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/yield">yield</a></code> keyword may not be used in an arrow function's body (except when permitted within functions further nested within it). As a consequence, arrow functions cannot be used as generators.</p> + +<h2 id="Function_body">Function body</h2> + +<p>Arrow functions can have either a "concise body" or the usual "block body".</p> + +<p>In a concise body, only an expression is specified, which becomes the explicit return value. In a block body, you must use an explicit <code>return</code> statement.</p> + +<pre class="brush: js">var func = x => x * x; +// concise body syntax, implied "return" + +var func = (x, y) => { return x + y; }; +// with block body, explicit "return" needed +</pre> + +<h2 id="Returning_object_literals">Returning object literals</h2> + +<p>Keep in mind that returning object literals using the concise body syntax <code>params => {object:literal}</code> will not work as expected.</p> + +<pre class="brush: js">var func = () => { foo: 1 }; +// Calling func() returns undefined! + +var func = () => { foo: function() {} }; +// SyntaxError: function statement requires a name</pre> + +<p>This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. <code>foo</code> is treated like a label, not a key in an object literal).</p> + +<p>Remember to wrap the object literal in parentheses.</p> + +<pre class="brush: js">var func = () => ({foo: 1});</pre> + +<h2 id="Line_breaks">Line breaks</h2> + +<p>An arrow function cannot contain a line break between its parameters and its arrow.</p> + +<pre class="brush: js">var func = () + => 1; +// SyntaxError: expected expression, got '=>'</pre> + +<h2 id="Parsing_order">Parsing order</h2> + +<p>Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a> compared to regular functions.</p> + +<pre class="brush: js">let callback; + +callback = callback || function() {}; // ok + +callback = callback || () => {}; +// SyntaxError: invalid arrow-function arguments + +callback = callback || (() => {}); // ok +</pre> + +<h2 id="More_examples">More examples</h2> + +<pre class="brush: js">// 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); +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.functions.arrow_functions")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://hacks.mozilla.org/2015/06/es6-in-depth-arrow-functions/">"ES6 In Depth: Arrow functions" on hacks.mozilla.org</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/functions/get/index.html b/files/pl/web/javascript/reference/functions/get/index.html new file mode 100644 index 0000000000..0c4cf664dc --- /dev/null +++ b/files/pl/web/javascript/reference/functions/get/index.html @@ -0,0 +1,216 @@ +--- +title: getter +slug: Web/JavaScript/Reference/Functions/get +translation_of: Web/JavaScript/Reference/Functions/get +--- +<div>{{jsSidebar("Functions")}}</div> + +<div>Składnia <strong>get </strong>łączy właściwość obiektu z funkcją, która będzie wykonywana za każdym razem, kiedy ta właściwość jest wywoływana.</div> + +<div></div> + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox">{get <em>prop</em>() { ... } } +{get <em>[expression]</em>() { ... } }</pre> + +<h3 id="Parametry">Parametry</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>Nazwa właściwości, która łączy ją z okresloną funkcją.</dd> + <dt>expression</dt> + <dd>Począwszy od ECMAScript 2015, można również użyć wyrażeń w celu połaczenia funkcji z nazwą właściwości, która jest obliczana.</dd> +</dl> + +<h2 id="Opis">Opis</h2> + +<p>Czasami pożądane jest aby umożliwić dostęp do właściwości, która zwraca wartość obliczaną dynamicznie lub potrzeba odzwierciedlić stan jakiejś wewnętrznej zmiennej bez potrzeby użycia wyraźnego wywołania metody. W języku JavaScript może to być osiągnięte dzięki użyciu <em>gettera</em>. Nie jest możliwe jednocześnie mieć getter połączony z właściwością i mieć tą właściwość (o takiej samej nazwie jak getter), która faktycznie trzyma wartość. Jednakże jest możliwe aby używać połączenia gettera i settera, żeby utworzyć rodzaj pseudo-właściwości.</p> + +<p>Zauważ, że gdy pracujemy ze składnią get to:</p> + +<div> +<ul> + <li>Można mieć identyfikator, który jest zarówno typu number jak i string;</li> + <li>Obowiązkowe jest aby zawierała dokładnie zero parametrów (zobacz: "<a href="http://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/">Niekompatybilna zmiana ES5: literał dla funkcji gettera i setera muszą teraz mieć dokładnie zero albo jeden argumentów</a>", aby uzyskać więcej informacji)</li> + <li>Nie może pojawiać się w literale obiektu z innym getem lub właściwością o takich samych nazwach (<code>{ get x() { }, get x() { } }</code> oraz <code>{ x: ..., get x() { } }</code> są niedozwolone).</li> +</ul> +</div> + +<p>Getter może być usunięty poprzez operator <code><a href="/pl/docs/Web/JavaScript/Referencje/Operatory/Operator_delete" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator">delete</a></code>.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Definiowanie_gettera_na_nowym_obiekcie_w_inicjalizatorze_obiektu.">Definiowanie gettera na nowym obiekcie w inicjalizatorze obiektu.</h3> + +<p>To stworzy pseudowłaściwość <code>latest</code> dla obiektu <code>obj</code>, która zwróci ostatnio zalogowany element w tablicy <code>log</code>.</p> + +<pre class="brush: js">var obj = { + log: ['test'], + get latest() { + if (this.log.length == 0) return undefined; + return this.log[this.log.length - 1]; + } +} +console.log(obj.latest); // Zwróci "test". +</pre> + +<p>Zauważ, że usiłowanie przypisania wartości do <code>latest</code> nie zmieni jej.</p> + +<h3 id="Usuwanie_gettera_używając_operatora_delete">Usuwanie gettera używając operatora <code>delete</code></h3> + +<p>Jeśli chcesz usunąć getter, wystarczy użyć <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a> </code>:</p> + +<pre class="brush: js">delete obj.latest; +</pre> + +<h3 id="Definiowanie_gettera_na_istniejącym_obiekcie_uzywając_defineProperty">Definiowanie gettera na istniejącym obiekcie uzywając <code>defineProperty</code></h3> + +<p>Aby dołączyć getter do istniejącego obiektu, można w każdej chwili użyć:<br> + {{jsxref("Object.defineProperty()")}}.</p> + +<pre class="brush: js">var o = {a: 0}; + +Object.defineProperty(o, 'b', { get: function() { return this.a + 1; } }); + +console.log(o.b) // Uruchamia getter, który otrzymuje yields a + 1 (which is 1)</pre> + +<h3 id="Używanie_obliczanych_wartości_dla_właściwości.">Używanie obliczanych wartości dla właściwości.</h3> + +<pre class="brush: js">var expr = 'foo'; + +var obj = { + get [expr]() { return 'bar'; } +}; + +console.log(obj.foo); // "bar"</pre> + +<h3 id="Bystre_samo-nadpisujące_leniwe_gettery">Bystre / samo-nadpisujące / leniwe gettery</h3> + +<p>Gettery dają ci możliwośc zdefiniowania właściwości obiektu, ale nie obliczają wartości właściwości dopóki nie jest ona dostępna. Getter odracza koszt obliczania wartości dopóki ta wartość jest potrzebna, a jeśli nigdy nie jest potrzebna, nie ponosi się tego kosztu.</p> + +<p>Dodatkową techniką optymalizacyjna aby uleniwić lub opóźnić obliczanie wartości dla właściwości jak i przechować ją na później są <strong>bystre (smart) lub <a href="https://en.wikipedia.org/wiki/Memoization">zmemoizowane</a> gettery.</strong> Wartość jest obliczana gdy getter jest wywoływany za pierwszym razem, a potem jest przechowywana więc kolejne dostępy zwracają zbuforowaną wartość bez jej ponownego obliczania. Jest to użyteczne w następujących sytuacjach:</p> + +<ul> + <li>Jeśli obliczanie wartości dla właściwości jest kosztowne (wymaga zużycia dużych zasobów pamięci operacyjnej RAM lub czasu procesora, itd).</li> + <li>Jesli wartość nie jest potrzebna natychmiast. Będzie jednak używana później lub w pewnych przypadkach nie będzie użyta wcale.</li> + <li>Jeżeli jest użyta, będzie wykorzystywana wiele razy i nie ma potrzeby ponownego jej oblczania, oraz jej wartość nigdy nie będzie zmieniona lub ponownie obliczana.</li> +</ul> + +<p>To oznacza, że nie powinno się używać leniwych getterów dla właściwości, której wartość może ulec zmianie, ponieważ taki getter nie oblicza właściwości ponownie.</p> + +<p>W następującym przykładzie obiekt posiada getter jako swoją właściwość. Otrzymując tą właściwość, jest ona usuwana z obiektu i ponownie dodawana, ale niejawnie jako właściwość z przypisanymi danymi. W ostatecznym rozrachunku zwracana jest wartość.</p> + +<pre class="brush: js">get notifier() { + delete this.notifier; + return this.notifier = document.getElementById('bookmarked-notification-anchor'); +},</pre> + +<p>Na potrzeby kodu Firefoxa, zobacz również moduł z kodem XPCOMUtils.jsm, który okresla funkcje <code><a href="/en-US/docs/Mozilla/JavaScript_code_modules/XPCOMUtils.jsm#defineLazyGetter()">defineLazyGetter()</a></code>.</p> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacje</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Added computed property names.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Zgodność_z_przeglądarkami">Zgodność z przeglądarkami</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(1)}}</td> + <td>{{ CompatGeckoDesktop("1.8.1") }}</td> + <td>{{ CompatIE(9) }}</td> + <td>9.5</td> + <td>3</td> + </tr> + <tr> + <td>Computed property names</td> + <td>{{CompatChrome(46)}}</td> + <td>{{ CompatGeckoDesktop("34") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoMobile("1.8.1") }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Computed property names</td> + <td>47</td> + <td>{{CompatNo}}</td> + <td>{{ CompatGeckoMobile("34.0") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Zobacz_również">Zobacz również</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setter</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li> + <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li> +</ul> diff --git a/files/pl/web/javascript/reference/functions/index.html b/files/pl/web/javascript/reference/functions/index.html new file mode 100644 index 0000000000..e7935d3318 --- /dev/null +++ b/files/pl/web/javascript/reference/functions/index.html @@ -0,0 +1,657 @@ +--- +title: Functions +slug: Web/JavaScript/Reference/Functions +tags: + - Constructor + - Function + - Functions + - JavaScript + - NeedsTranslation + - Parameter + - TopicStub + - parameters +translation_of: Web/JavaScript/Reference/Functions +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> 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 <em>function body</em>. Values can be <em>passed</em> to a function, and the function will <em>return</em> a value.</p> + +<p>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 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects.</p> + +<p>For more examples and explanations, see also the <a href="/en-US/docs/Web/JavaScript/Guide/Functions">JavaScript guide about functions</a>.</p> + +<h2 id="Description">Description</h2> + +<p>Every function in JavaScript is a <code>Function</code> object. See {{jsxref("Function")}} for information on properties and methods of <code>Function</code> objects.</p> + +<p>To return a value other than the default, a function must have a <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a></code> statement that specifies the value to return. A function without a return statement will return a default value. In the case of a <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor">constructor</a> called with the <code><a href="/en-US/docs/Web/JavaScript/Reference/Operators/new">new</a></code> keyword, the default value is the value of its <code>this</code> parameter. For all other functions, the default return value is {{jsxref("undefined")}}.</p> + +<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>. 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:</p> + +<pre class="brush: js">/* 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); +</pre> + +<p>The <a href="/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body.</p> + +<h2 id="Defining_functions">Defining functions</h2> + +<p>There are several ways to define functions:</p> + +<h3 id="The_function_declaration_(function_statement)">The function declaration (<code>function</code> statement)</h3> + +<p>There is a special syntax for declaring functions (see <a href="/en-US/docs/Web/JavaScript/Reference/Statements/function">function statement</a> for details):</p> + +<pre class="syntaxbox">function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_function_expression_(function_expression)">The function expression (<code>function</code> expression)</h3> + +<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/function">function expression</a> 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 <em>hoisted</em> onto the beginning of the scope, therefore they cannot be used before they appear in the code.</p> + +<pre class="syntaxbox">function [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<p>Here is an example of an <strong>anonymous</strong> function expression (the <code>name</code> is not used):</p> + +<pre class="brush: js">var myFunction = function() { + statements +}</pre> + +<p>It is also possible to provide a name inside the definition in order to create a <strong>named</strong> function expression:</p> + +<pre class="brush: js">var myFunction = function namedFunction(){ + statements +} +</pre> + +<p>One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.</p> + +<p>As we can see, both example do not start with the <code>function</code> keyword. Statements involving functions which do not start with <code>function</code> are function expressions.</p> + +<p>When function are used only once, a common pattern is an <strong>IIFE (<em>Immediately Invokable Function Expressions</em>)</strong>.</p> + +<pre class="brush: js">(function() { + statements +})();</pre> + +<p>IIFE are function expression that are invoked as soon as the function is declared.</p> + +<h3 id="The_generator_function_declaration_(function*_statement)">The generator function declaration (<code>function*</code> statement)</h3> + +<p>There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):</p> + +<pre class="syntaxbox">function* <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> +</dl> + +<dl> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_generator_function_expression_(function*_expression)">The generator function expression (<code>function*</code> expression)</h3> + +<p>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):</p> + +<pre class="syntaxbox">function* [<em>name</em>]([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { + <em>statements</em> +} +</pre> + +<dl> + <dt><code>name</code></dt> + <dd>The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd> +</dl> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd> + <dt><code>statements</code></dt> + <dd>The statements comprising the body of the function.</dd> +</dl> + +<h3 id="The_arrow_function_expression_(>)">The arrow function expression (=>)</h3> + +<p>An arrow function expression has a shorter syntax and lexically binds its <code>this</code> value (see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> for details):</p> + +<pre class="syntaxbox">([param[, param]]) => { + statements +} + +param => expression +</pre> + +<dl> + <dt><code>param</code></dt> + <dd>The name of an argument. Zero arguments need to be indicated with <code>()</code>. For only one argument, the parentheses are not required. (like <code>foo => 1</code>)</dd> + <dt><code>statements or expression</code></dt> + <dd>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.</dd> +</dl> + +<h3 id="The_Function_constructor">The <code>Function</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>Function</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("Function")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function body.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h3 id="The_GeneratorFunction_constructor">The <code>GeneratorFunction</code> constructor</h3> + +<div class="note"> +<p><strong>Note:</strong> <code>GeneratorFunction</code> is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> Using the <code>GeneratorFunction</code> 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.</p> +</div> + +<p>As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the <code>new</code> operator:</p> + +<pre class="syntaxbox">new GeneratorFunction (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>) +</pre> + +<dl> + <dt><code>arg1, arg2, ... arg<em>N</em></code></dt> + <dd>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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd> +</dl> + +<dl> + <dt><code>functionBody</code></dt> + <dd>A string containing the JavaScript statements comprising the function definition.</dd> +</dl> + +<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p> + +<h2 id="Function_parameters">Function parameters</h2> + +<h3 id="Default_parameters">Default parameters</h3> + +<p>Default function parameters allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed. For more details, see<a href="/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters"> default parameters</a>.</p> + +<h3 id="Rest_parameters">Rest parameters</h3> + +<p>The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see <a href="/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameters</a>.</p> + +<h2 id="The_arguments_object">The <code>arguments</code> object</h2> + +<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a>.</p> + +<ul> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments">arguments</a></code>: An array-like object containing the arguments passed to the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code> {{Deprecated_inline}}: The currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a></code> {{Obsolete_inline}} : The function that invoked the currently executing function.</li> + <li><code><a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a></code>: The number of arguments passed to the function.</li> +</ul> + +<h2 id="Defining_method_functions">Defining method functions</h2> + +<h3 id="Getter_and_setter_functions">Getter and setter functions</h3> + +<p>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.</p> + +<dl> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">get</a></dt> + <dd> + <p>Binds an object property to a function that will be called when that property is looked up.</p> + </dd> + <dt><a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">set</a></dt> + <dd>Binds an object property to a function to be called when there is an attempt to set that property.</dd> +</dl> + +<h3 id="Method_definition_syntax">Method definition syntax</h3> + +<p>Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See <a href="/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions">method definitions</a> for more information.</p> + +<pre class="brush: js">var obj = { + foo() {}, + bar() {} +};</pre> + +<h2 id="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h2> + +<p>Compare the following:</p> + +<p>A function defined with the <code>Function</code> constructor assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = new Function('x', 'y', 'return x * y');</pre> + +<p>A <em>function declaration</em> of a function named <code>multiply</code>:</p> + +<pre class="brush: js">function multiply(x, y) { + return x * y; +} // there is no semicolon here +</pre> + +<p>A <em>function expression</em> of an anonymous function assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function(x, y) { + return x * y; +}; +</pre> + +<p>A <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply:</code></p> + +<pre class="brush: js">var multiply = function func_name(x, y) { + return x * y; +}; +</pre> + +<h3 id="Differences">Differences</h3> + +<p>All do approximately the same thing, with a few subtle differences:</p> + +<p>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 <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:</p> + +<pre class="brush: js">var y = function x() {}; +alert(x); // throws an error +</pre> + +<p>The function name also appears when the function is serialized via <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p> + +<p>On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.</p> + +<p>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:</p> + +<p>A function defined by '<code>new Function'</code> does not have a function name. However, in the <a href="/en-US/docs/Mozilla/Projects/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:</p> + +<pre class="brush: js">function anonymous() { +} +</pre> + +<p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p> + +<pre class="brush: js">var foo = new Function("alert(anonymous);"); +foo(); +</pre> + +<p>Unlike functions defined by function expressions or by the <code>Function</code> constructor, a function defined by a function declaration can be used before the function declaration itself. For example:</p> + +<pre class="brush: js">foo(); // alerts FOO! +function foo() { + alert('FOO!'); +} +</pre> + +<p>A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</p> + +<p>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> 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 "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should generally be avoided whenever possible.</p> + +<p>It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> 's string aren't parsed repeatedly. For example:</p> + +<pre class="brush: js">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.</pre> + +<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p> + +<ul> + <li>becomes part of an expression</li> + <li>is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:</li> +</ul> + +<pre class="brush: js">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 + } +} +</pre> + +<h3 id="Examples">Examples</h3> + +<pre class="brush: js">// 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() {} + } +} +</pre> + +<h2 id="Block-level_functions">Block-level functions</h2> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.</p> + +<pre class="brush: js">'use strict'; + +function f() { + return 1; +} + +{ + function f() { + return 2; + } +} + +f() === 1; // true + +// f() === 2 in non-strict mode +</pre> + +<h3 id="Block-level_functions_in_non-strict_code">Block-level functions in non-strict code</h3> + +<p>In a word: Don't.</p> + +<p>In non-strict code, function declarations inside blocks behave strangely. For example:</p> + +<pre class="brush: js">if (shouldDefineZero) { + function zero() { // DANGER: compatibility risk + console.log("This is zero."); + } +} +</pre> + +<p>ES2015 says that if <code>shouldDefineZero</code> is false, then <code>zero</code> 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 <code>zero</code> whether the block executed or not.</p> + +<p>In <a href="/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, all browsers that support ES2015 handle this the same way: <code>zero</code> is defined only if <code>shouldDefineZero</code> is true, and only in the scope of the <code>if</code>-block.</p> + +<p>A safer way to define functions conditionally is to assign a function expression to a variable:</p> + +<pre class="brush: js">var zero; +if (0) { + zero = function() { + console.log("This is zero."); + }; +} +</pre> + +<h2 id="Examples_2">Examples</h2> + +<h3 id="Returning_a_formatted_number">Returning a formatted number</h3> + +<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p> + +<pre class="brush: js">// 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; +} +</pre> + +<p>The following statements call the padZeros function.</p> + +<pre class="brush: js">var result; +result = padZeros(42,4); // returns "0042" +result = padZeros(42,2); // returns "42" +result = padZeros(5,4); // returns "0005" +</pre> + +<h3 id="Determining_whether_a_function_exists">Determining whether a function exists</h3> + +<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is performed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p> + +<pre class="brush: js"> if ('function' == typeof window.noFunc) { + // use noFunc() + } else { + // do something else + } +</pre> + +<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES1')}}</td> + <td>{{Spec2('ES1')}}</td> + <td>Initial definition. Implemented in JavaScript 1.0</td> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td> </td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>New: Arrow functions, Generator functions, default parameters, rest parameters.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>39</td> + <td>{{CompatGeckoDesktop("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatChrome(45.0)}}</td> + <td>{{CompatGeckoDesktop("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatOpera(32)}}</td> + <td>10</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoDesktop("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Generator functions</td> + <td>{{CompatUnknown}}</td> + <td>39</td> + <td>{{CompatGeckoMobile("26.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>26</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Arrow functions</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatGeckoMobile("22.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td>Block-level functions</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatGeckoMobile("46.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Statements/function", "function statement")}}</li> + <li>{{jsxref("Operators/function", "function expression")}}</li> + <li>{{jsxref("Statements/function*", "function* statement")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Function")}}</li> + <li>{{jsxref("GeneratorFunction")}}</li> + <li>{{jsxref("Functions/Arrow_functions", "Arrow functions")}}</li> + <li>{{jsxref("Functions/Default_parameters", "Default parameters")}}</li> + <li>{{jsxref("Functions/rest_parameters", "Rest parameters")}}</li> + <li>{{jsxref("Functions/arguments", "Arguments object")}}</li> + <li>{{jsxref("Functions/get", "getter")}}</li> + <li>{{jsxref("Functions/set", "setter")}}</li> + <li>{{jsxref("Functions/Method_definitions", "Method definitions")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope">Functions and function scope</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/functions/parametry_domyślne/index.html b/files/pl/web/javascript/reference/functions/parametry_domyślne/index.html new file mode 100644 index 0000000000..b192456adf --- /dev/null +++ b/files/pl/web/javascript/reference/functions/parametry_domyślne/index.html @@ -0,0 +1,225 @@ +--- +title: Parametry domyślne +slug: Web/JavaScript/Reference/Functions/Parametry_domyślne +tags: + - ECMAScript2015 + - Funkcje + - JavaScript +translation_of: Web/JavaScript/Reference/Functions/Default_parameters +--- +<div>{{jsSidebar("Functions")}}</div> + +<p><span class="seoSummary"><strong>Domyślne parametry funkcji</strong> pozwalają na inicjalizację nazwanych parametrów wartościami domyślnymi tam, gdzie nie została podana żadna wartość lub jako wartość podano <code>undefined</code>.</span></p> + +<div>{{EmbedInteractiveExample("pages/js/functions-default.html")}}</div> + + + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox">function [nazwa]([parametr1[ = domyślnaWartość1 ][, ..., parametrN[ = domyślnaWartośćN ]]]) { + ciało funkcji +} +</pre> + +<h2 id="Opis">Opis</h2> + +<p>W języku JavaScript domyślną wartością parametrów funkcji jest <code>{{jsxref("undefined")}}</code>. Często jednak dobrze jest ustawić inną wartość domyślną – wówczas parametry domyślne okazują się pomocne.</p> + +<p>W przeszłości, ogólną strategią na ustawianie domyślnych wartości było sprawdzanie parametrów w ciele funkcji – w sytuacji, w których były one równe <code>undefined</code>, przypisywano im konkretne wartości.</p> + +<p>W następującym przykładzie, jeśli żadna wartość nie jest podana jako <code>b</code>, kiedy wywoływana jest funkcja <code>pomnóż</code>, wartość <code>b</code> powinna być równa <code>undefined</code> – wówczas funkcja powinna zwrócić <code>NaN</code> jako wynik operacji <code>a * b</code>.</p> + +<pre class="brush: js">function pomnóż(a, b) { + return a * b; +} + +pomnóż(5, 2); // 10 +pomnóż(5); // NaN ! +</pre> + +<p>Aby się przed tym uchronić, należy użyć czegoś takiego, jak w drugiej linijce, gdzie wartość <code>b</code> jest ustawiana na <code>1</code>, jeśli funkcja <code>pomnóż</code> jest wywoływana tylko z jednym argumentem.</p> + +<pre class="brush: js">function pomnóż(a, b) { + b = (typeof b !== 'undefined') ? b : 1; + return a * b; +} + +pomnóż(5, 2); // 10 +pomnóż(5); // 5 +</pre> + +<p>Dzięki parametrom domyślnym w ES2015, tego rodzaju sprawdzanie wartości parametrów w ciele funkcji nie jest już konieczne. Można teraz przypisać <code>1</code> jako domyślną wartość w nagłówku funkcji:</p> + +<pre class="brush: js">function pomnóż(a, b = 1) { + return a * b; +} + +pomnóż(5, 2); // 10 +pomnóż(5); // 5 +</pre> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Przekazywanie_undefined_kontra_inne_puste_wartości">Przekazywanie <code>undefined</code> kontra inne <em>puste wartości</em></h3> + +<p>W drugim wywołaniu funkcji w tym przykłądzie, nawet jeśli jako pierwszy argument wprost podany <code>undefined</code> (jednak nie <code>null</code> lub inne <em><a href="/en-US/docs/Glossary/Falsy">puste</a> wartości</em>), wartością argumentu <code>num</code> dalej będzie wartość domyślna.</p> + +<pre class="brush: js">function test(num = 1) { + console.log(typeof num); +} + +test(); // 'number' (num jest ustawiany na 1) +test(undefined); // 'number' (num również jest ustawiany na 1) + +// test z innymi "pustymi" wartościami: +test(''); // 'string' (num jest ustawiany na '') +test(null); // 'object' (num jest ustawiany na null) +</pre> + +<h3 id="Ewaluacja_w_czasie_wykonania">Ewaluacja w czasie wykonania</h3> + +<p>Domyślne argumenty są przypisywane w czasie wykonania, a więc w odróżnieniu od np. Pythona, nowy obiekt jest tworzony przy każdym wywołaniu funkcji.</p> + +<pre class="brush: js">function append(wartość, tablica = []) { + array.push(wartość); + return tablica; +} + +append(1); //[1] +append(2); //[2], nie [1, 2] +</pre> + +<p>Dotyczy to również funkcji i zmiennych:</p> + +<pre class="brush: js">function callSomething(thing = something()) { + return thing; +} + +let numberOfTimesCalled = 0; +function something() { + numberOfTimesCalled += 1; + return numberOfTimesCalled; +} + +callSomething(); // 1 +callSomething(); // 2</pre> + +<h3 id="Domyślne_parametry_są_dostępne_dla_późniejszych_domyślnych_parametrów">Domyślne parametry są dostępne dla późniejszych domyślnych parametrów</h3> + +<p>Parametry zdefiniowane wcześniej (bardziej na lewo na liście parametrów), są dostępne dla domyślnych parametrów definiowanych później:</p> + +<pre class="brush: js">function pozdrów(imię, pozdrowienie, wiadomość = pozdrowienie + ' ' + imię) { + return [imię, pozdrowienie, wiadomość]; +} + +pozdrów('Dawid', 'Cześć'); // ["Dawid", "Cześć", "Cześć Dawid"] +pozdrów('Dawid', 'Cześć', 'Wszystkiego najlepszego!'); // ["Dawid", "Cześć", "Wszystkiego najlepszego!"] +</pre> + +<p>Ta funkcjonalność może być przybliżona w ten sposób, pokazujący, jak wiele przypadków brzegowych może być obsłużonych:</p> + +<pre class="brush: js">function go() { + return ':P'; +} + +function withDefaults(a, b = 5, c = b, d = go(), e = this, + f = arguments, g = this.value) { + return [a, b, c, d, e, f, g]; +} + +function withoutDefaults(a, b, c, d, e, f, g) { + switch (arguments.length) { + case 0: + a; + case 1: + b = 5; + case 2: + c = b; + case 3: + d = go(); + case 4: + e = this; + case 5: + f = arguments; + case 6: + g = this.value; + default: + } + return [a, b, c, d, e, f, g]; +} + +withDefaults.call({value: '=^_^='}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] + +withoutDefaults.call({value: '=^_^='}); +// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] +</pre> + +<h3 id="Funkcje_definiowane_w_ciele_funkcji">Funkcje definiowane w ciele funkcji</h3> + +<p>Wprowadzone w Gecko 33 {{geckoRelease(33)}}. Funkcje deklarowane w ciele funkcji nie mogą być używane jako wartości domyślne w tej samej funkcji. Przy takiej próbie, wyrzucany jest jest {{jsxref("ReferenceError")}}. Parametr domyślny zawsze wykonywany jest jako pierwszy, a więc deklaracje w ciele funkcji są ewaluowane później.</p> + +<pre class="brush: js">// Nie działa! Wyrzuca ReferenceError. +function f(a = go()) { + function go() { return ':P'; } +} +</pre> + +<h3 id="Parametry_bez_wartości_domyślnych_po_parametrach_domyślnych">Parametry bez wartości domyślnych po parametrach domyślnych</h3> + +<p>Przed Gecko 26 {{geckoRelease(26)}}, poniższy kod zwracał {{jsxref("SyntaxError")}}. Zostało to naprawione w {{bug(777060)}}. Wartości parametrów dalej są ustawiane w kolejności od lewej do prawej, nadpisując domyślne parametry, nawet jeśli występują potem parametry bez wartości domyślnych.</p> + +<pre class="brush: js">function f(x = 1, y) { + return [x, y]; +} + +f(); // [1, undefined] +f(2); // [2, undefined] +</pre> + +<h3 id="Parametr_destrukturyzowany_z_przypisaniem_domyślnej_wartości">Parametr destrukturyzowany z przypisaniem domyślnej wartości</h3> + +<p>Możesz też użyć przypisania domyślnej wartości z notacją <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">parametru destruktyryzowanego</a>:</p> + +<pre class="brush: js">function f([x, y] = [1, 2], {z: z} = {z: 3}) { + return x + y + z; +} + +f(); // 6</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + <th scope="col">Status</th> + <th scope="col">Komentarz</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Wsparcie_przeglądarek">Wsparcie przeglądarek</h2> + +<div> + + +<p>{{Compat("javascript.functions.default_parameters")}}</p> +</div> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a class="external" href="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values" rel="external" title="http://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values">Original proposal at ecmascript.org</a></li> +</ul> diff --git a/files/pl/web/javascript/reference/functions/set/index.html b/files/pl/web/javascript/reference/functions/set/index.html new file mode 100644 index 0000000000..d3eb6ad31d --- /dev/null +++ b/files/pl/web/javascript/reference/functions/set/index.html @@ -0,0 +1,146 @@ +--- +title: setter +slug: Web/JavaScript/Reference/Functions/set +translation_of: Web/JavaScript/Reference/Functions/set +--- +<div>{{jsSidebar("Functions")}}</div> + +<p>Składnia <strong><code>set</code></strong> wiąże właściwość obiektu z funkcją, która zostanie wywołana przy próbie przypisania wartości danej właściwości.</p> + +<div>{{EmbedInteractiveExample("pages/js/functions-setter.html")}}</div> + + + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox">{set <em>prop</em>(<em>val</em>) { . . . }} +{set [expression](<em>val</em>) { . . . }}</pre> + +<h3 id="Parametry">Parametry</h3> + +<dl> + <dt><code>prop</code></dt> + <dd>Nazwa właściwości wiązanej z określoną funkcją.</dd> +</dl> + +<dl> + <dt><code>val</code></dt> + <dd>Zmienna przechowująca wartość przekazaną do przypisania do właściwości <code>prop.</code></dd> + <dt>expression</dt> + <dd>Począwszy od ECMAScript 2015, można również użyć wyrażeń w celu połaczenia funkcji z nazwą właściwości, która jest obliczana.</dd> +</dl> + +<h2 id="Description">Description</h2> + +<p>Setter może być użyty do wywołania określonej funkcji przy każdej próbie przypisania wartości do danej właściwości. Settery są najczęściej używane razem z getterami żeby utworzyć rodzaj pseudo-właściwości. Nie ma możliwości jednoczesnego używania settera oraz faktycznej wartości przypisanej do danej właściwości.</p> + +<p>Uwagi do składni <code>set</code>:</p> + +<div> +<ul> + <li>Można utworzyć identyfikator typu number lub string;</li> + <li>Setter musi mieć jeden paramter (sprawdź szczegóły <a class="external" href="http://whereswalden.com/2010/08/22/incompatible-es5-change-literal-getter-and-setter-functions-must-now-have-exactly-zero-or-one-arguments/" rel="external nofollow">Niekompatybilna zmiana <abbr title="ECMAScript 5th edition">ES5</abbr>: gettery i settery muszą mieć dokładnie zero lub one argument</a>);</li> + <li>Setter nie może być zdefiniowany kilkukrotnie dla danej właściwości. Jednoczesne użycie settera i faktycznej wartości przypisanej do właściwości jest zabronione<br> + ( <code>{ set x(v) { }, set x(v) { } }</code> oraz <code>{ x: ..., set x(v) { } }</code> są zabronione)</li> +</ul> +</div> + +<p>Setter może być usunięty przy użyciu operatora <a href="/en-US/docs/Web/JavaScript/Reference/Operators/delete" title="en-US/docs/JavaScript/Reference/Operators/Special/delete"><code>delete</code></a>.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Definicja_settera_w_nowym_obiekcie_podczas_inicjalizacji">Definicja settera w nowym obiekcie podczas inicjalizacji</h3> + +<p>Poniższa składnia definiuje pseudo-właściwość <code>current</code> obiektu <font face="consolas, Liberation Mono, courier, monospace">language</font>, która podczas przypisania wartości aktualizuje tablicę <code>log</code> o tą wartość:</p> + +<pre class="brush: js">var language = { + set current(name) { + this.log.push(name); + }, + log: [] +} + +language.current = 'EN'; +console.log(language.log); // ['EN'] + +language.current = 'FA'; +console.log(language.log); // ['EN', 'FA'] +</pre> + +<p>Zwróć uwagę, że właściwość <code>current</code> nie jest zdefiniowana i próby odczytu zwrócą <code>undefined</code>.</p> + +<h3 id="Usuwanie_settera_przy_użyciu_operatora_delete">Usuwanie settera przy użyciu operatora <code>delete</code></h3> + +<p>Setter może zostać usunięty przy użyciu <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>:</p> + +<pre class="brush: js">delete o.current; +</pre> + +<h3 id="Definicja_settera_dla_istniejącego_obiektu_przy_użyciu_defineProperty">Definicja settera dla istniejącego obiektu przy użyciu <code>defineProperty</code></h3> + +<p>Aby zdefiniować setter dla istniejącego obiektu po jego uprzednim utworzeniu użyj {{jsxref("Object.defineProperty()")}}.</p> + +<pre class="brush: js">var o = {a: 0}; + +Object.defineProperty(o, 'b', { set: function(x) { this.a = x / 2; } }); + +o.b = 10; // Uruchamia setter, który przypisuje 10 / 2 (5) do właściwości 'a' +console.log(o.a) // 5</pre> + +<h3 id="Używanie_wyrażenia_do_obliczenia_nazwy_settera">Używanie wyrażenia do obliczenia nazwy settera</h3> + +<pre class="brush: js">var expr = 'foo'; + +var obj = { + baz: 'bar', + set [expr](v) { this.baz = v; } +}; + +console.log(obj.baz); // "bar" +obj.foo = 'baz'; // uruchom setter +console.log(obj.baz); // "baz" +</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}</td> + <td>{{Spec2('ES5.1')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Added computed property names.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-method-definitions', 'Method definitions')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Zgodność_z_przeglądarkami">Zgodność z przeglądarkami</h2> + + + +<p>{{Compat("javascript.functions.set")}}</p> + +<h2 id="Zobacz_również">Zobacz również</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getter</a></li> + <li>{{jsxref("Operators/delete", "delete")}}</li> + <li>{{jsxref("Object.defineProperty()")}}</li> + <li>{{jsxref("Object.defineGetter", "__defineGetter__")}}</li> + <li>{{jsxref("Object.defineSetter", "__defineSetter__")}}</li> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Defining_getters_and_setters">Defining Getters and Setters</a> in JavaScript Guide</li> +</ul> |