From de5c456ebded0e038adbf23db34cc290c8829180 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:49:24 +0100 Subject: unslug pl: move --- .../reference/operators/comma_operator/index.html | 37 ++ .../operators/conditional_operator/index.html | 34 ++ .../reference/operators/delete/index.html | 74 ++++ .../operators/destructuring_assignment/index.html | 493 +++++++++++++++++++++ .../reference/operators/function/index.html | 144 ++++++ .../reference/operators/function_star_/index.html | 90 ++++ .../reference/operators/grouping/index.html | 90 ++++ .../javascript/reference/operators/in/index.html | 92 ++++ .../web/javascript/reference/operators/index.html | 282 ++++++++++++ .../reference/operators/instanceof/index.html | 168 +++++++ .../reference/operators/new.target/index.html | 134 ++++++ .../javascript/reference/operators/new/index.html | 183 ++++++++ .../nullish_coalescing_operator/index.html | 251 +++++++++++ .../operators/object_initializer/index.html | 387 ++++++++++++++++ .../operators/operator_precedence/index.html | 336 ++++++++++++++ .../operators/pipeline_operator/index.html | 65 +++ .../operators/property_accessors/index.html | 177 ++++++++ .../reference/operators/spread_syntax/index.html | 244 ++++++++++ .../reference/operators/super/index.html | 171 +++++++ .../javascript/reference/operators/this/index.html | 346 +++++++++++++++ .../reference/operators/typeof/index.html | 91 ++++ .../javascript/reference/operators/void/index.html | 51 +++ .../reference/operators/yield/index.html | 168 +++++++ .../reference/operators/yield_star_/index.html | 200 +++++++++ 24 files changed, 4308 insertions(+) create mode 100644 files/pl/web/javascript/reference/operators/comma_operator/index.html create mode 100644 files/pl/web/javascript/reference/operators/conditional_operator/index.html create mode 100644 files/pl/web/javascript/reference/operators/delete/index.html create mode 100644 files/pl/web/javascript/reference/operators/destructuring_assignment/index.html create mode 100644 files/pl/web/javascript/reference/operators/function/index.html create mode 100644 files/pl/web/javascript/reference/operators/function_star_/index.html create mode 100644 files/pl/web/javascript/reference/operators/grouping/index.html create mode 100644 files/pl/web/javascript/reference/operators/in/index.html create mode 100644 files/pl/web/javascript/reference/operators/index.html create mode 100644 files/pl/web/javascript/reference/operators/instanceof/index.html create mode 100644 files/pl/web/javascript/reference/operators/new.target/index.html create mode 100644 files/pl/web/javascript/reference/operators/new/index.html create mode 100644 files/pl/web/javascript/reference/operators/nullish_coalescing_operator/index.html create mode 100644 files/pl/web/javascript/reference/operators/object_initializer/index.html create mode 100644 files/pl/web/javascript/reference/operators/operator_precedence/index.html create mode 100644 files/pl/web/javascript/reference/operators/pipeline_operator/index.html create mode 100644 files/pl/web/javascript/reference/operators/property_accessors/index.html create mode 100644 files/pl/web/javascript/reference/operators/spread_syntax/index.html create mode 100644 files/pl/web/javascript/reference/operators/super/index.html create mode 100644 files/pl/web/javascript/reference/operators/this/index.html create mode 100644 files/pl/web/javascript/reference/operators/typeof/index.html create mode 100644 files/pl/web/javascript/reference/operators/void/index.html create mode 100644 files/pl/web/javascript/reference/operators/yield/index.html create mode 100644 files/pl/web/javascript/reference/operators/yield_star_/index.html (limited to 'files/pl/web/javascript/reference/operators') diff --git a/files/pl/web/javascript/reference/operators/comma_operator/index.html b/files/pl/web/javascript/reference/operators/comma_operator/index.html new file mode 100644 index 0000000000..b037dcfdc8 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/comma_operator/index.html @@ -0,0 +1,37 @@ +--- +title: Operator przecinkowy +slug: Web/JavaScript/Referencje/Operatory/Operator_przecinkowy +tags: + - JavaScript + - Operator + - Przecinek + - Przecinkowy +translation_of: Web/JavaScript/Reference/Operators/Comma_Operator +--- +
{{jsSidebar("Operators")}}
+ +

+ +

Operator przecinkowy wykonuje wszystkie argumenty i zwraca wynik ostatniego argumentu.

+ +

Składnia

+ +
wyr1, wyr2, wyr3...
+ +

Parametry

+ +
+
wyr1, wyr2, wyr3
+
Wyrażenia, z których jedynie ostatnie jest zwracane.
+
+ +

Opis

+ +

Możemy zastosować operator przecinkowy, kiedy chcemy utworzyć wyrażenie składające się z kilku wyrażeń. Operator przecinkowy jest chyba najczęściej używany w instrukcji pętli for.

+ +

Na przykład, jeśli a jest tablicą dwuwymiarową z 10 elementami w sobie, następujący kod użyje operatora przecinkowego do zwiększenia dwóch zmiennych na raz. Kod wypisze wartości elementów ułożonych po przekątnej w tablicy:

+ +
var a = [[]];
+for (var i=0, j=9; i <= 9; i++, j--)
+   console.log("a["+i+","+j+"]= " + a[i,j])
+
diff --git a/files/pl/web/javascript/reference/operators/conditional_operator/index.html b/files/pl/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..b5b00d0aa1 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,34 @@ +--- +title: Operator warunkowy +slug: Web/JavaScript/Referencje/Operatory/Operator_warunkowy +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

Operator warunkowy jest jedynym operatorem w JavaScript, który pobiera trzy argumenty. Operator jest często stosowany jako skrócenie instrukcji if.

+ +

Składnia

+ +
warunek ? wyr1 : wyr2 
+ +

Parametry

+ +
+
warunek
+
Wyrażenie, które sprawdza czy warunek jest spełniony (true lub false).
+
+ +
+
wyr1, wyr2
+
Wyrażenia z wartością jakiegoś typu.
+
+ +

Opis

+ +

Jeśli warunek jest true, operator zwraca wartość wyr1; w przeciwnym razie zwraca wartość wyr2. Na przykład, do wyświetlenia różnych wiadomości opartych na wartości zmiennej isMember, będziesz mógł zastosować poniższą instrukcję:

+ +
console.log("Opłata wynosi " + (isMember ? "$2.00" : "$10.00"));
+console.log("Opłata wynosi " + (zarejestrowany == 1) ? "$2.00" : "$10.00");
+
diff --git a/files/pl/web/javascript/reference/operators/delete/index.html b/files/pl/web/javascript/reference/operators/delete/index.html new file mode 100644 index 0000000000..d2a3679804 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/delete/index.html @@ -0,0 +1,74 @@ +--- +title: Operator delete +slug: Web/JavaScript/Referencje/Operatory/Operator_delete +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Operators/delete +--- +
{{jsSidebar("Operators")}}
+ +

Operator delete usuwa obiekt, własność obiektu lub element w określonym indeksie w tablicy.

+ +

Składnia

+ +
delete  nazwaObiektu
+
+ +
delete nazwaObiektu.własność
+delete nazwaObiektu['własność']
+
+ +

Parametry

+ +
+
nazwaObiektu
+
Nazwa obiektu.
+
+ +
+
własność
+
Własność do usunięcia.
+
+ +

Opis

+ +

Czwarta forma jest dozwolona tylko wewnątrz instrukcji with w celu usunięcia własności z obiektu.

+ +

Możesz użyć operatora delete, aby usunąć zmienne zadeklarowane bezpośrednio, jednak nie możesz usunąć zmiennych zadeklarowanych za pomocą instrukcji var.

+ +

Jeśli operator delete zadziała prawidłowo, ustawi on własność lub element jako undefined (niezdefiniowany). Operator delete zwraca wartość true (prawda), jeśli operacja jest możliwa, zaś wartość false (fałsz), gdy operacja nie jest możliwa.

+ +
x = 42;
+var y = 43;
+myobj = new Number();
+myobj.h = 4;      // tworzy własność h
+delete x;         // zwraca true (można usuwać, jeśli zadeklarowano bezpośrednio)
+delete y;         // zwraca false (nie można usuwać, jeśli zadeklarowano za pomocą var)
+delete Math.PI;   // zwraca false (nie można usuwać własności predefiniowanych)
+delete myobj.h;   // zwraca true (można usuwać własności zdefiniowane przez użytkownika)
+delete myobj;     // zwraca true (można usuwać obiekty)
+
+ +

Usuwanie elementów tablicy

+ +

Gdy usuwasz element tablicy nie ma to wpływu na jej długość. Na przykład: jeśli usuniesz a{{ mediawiki.external(3) }}, a{{ mediawiki.external(4) }} będzie wciąż a{{ mediawiki.external(4) }}, natomiast a{{ mediawiki.external(3) }} będzie niezdefiniowane.

+ +

Gdy operator delete usuwa element tablicy, element ten przestaje już w niej istnieć. W poniższym przykładzie drzewa{{ mediawiki.external(3) }} jest usunięte za pomocą delete.

+ +
drzewa = new Array("sekwoja","wawrzyn","cedr","dąb","klon");
+delete drzewa[3];
+if (3 in drzewa) {
+   // to nie zostanie wykonane
+}
+
+ +

Jeśli chcesz, aby element tablicy nadal istniał, ale posiadał wartość niezdefiniowaną, użyj słowa kluczowego undefined zamiast operatora delete. W poniższym przykładzie, drzewa{{ mediawiki.external(3) }} jest przypisana wartość niezdefiniowana, ale element tablicy nadal istnieje:

+ +
drzewa = new Array("sekwoja","wawrzyn","cedr","dąb","klon");
+drzewa[3] = undefined;
+if (3 in drzewa) {
+   // to zostanie wykonane
+}
+
+ +
 
diff --git a/files/pl/web/javascript/reference/operators/destructuring_assignment/index.html b/files/pl/web/javascript/reference/operators/destructuring_assignment/index.html new file mode 100644 index 0000000000..851acea725 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/destructuring_assignment/index.html @@ -0,0 +1,493 @@ +--- +title: Przypisanie destrukturyzujące +slug: Web/JavaScript/Referencje/Operatory/Destructuring_assignment +translation_of: Web/JavaScript/Reference/Operators/Destructuring_assignment +--- +
{{jsSidebar("Operators")}}
+ +

Składnia przypisania destrukturyzującego jest wyrażeniem w JavaScript, które pozwala na wyciągnięcie danych z tablic bądź obiektów do odrębnych zmiennych.

+ +

Składnia

+ +
var a, b, rest;
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+[a, b, ...rest] = [1, 2, 3, 4, 5];
+console.log(a); // 1
+console.log(b); // 2
+console.log(rest); // [3, 4, 5]
+
+({a, b} = {a:1, b:2});
+console.log(a); // 1
+console.log(b); // 2
+
+// ES2016 - nie zaimplementowane w przeglądarce Firefox 47a01
+({a, b, ...rest} = {a:1, b:2, c:3, d:4}); 
+ +

Opis

+ +

Wyrażenie literału obiektowego i tablicowego umożliwiają łatwe tworzenie paczek danych ad-hoc

+ +
var x = [1, 2, 3, 4, 5];
+ +

Składnia przypisania destrukturyzacyjnego używa podobnej składni, ale z lewej strony przypisania definiujemy, które elementy wyciągnąć ze zmiennej źródłowej.

+ +
var x = [1, 2, 3, 4, 5];
+var [y, z] = x;
+console.log(y); // 1
+console.log(z); // 2
+
+ +

Funkcjonalność ta jest podobna do tych obecnych w językach takich jak Perl i Python.

+ +

Destrukturyzacja tablic

+ +

Podstawowe przypisanie zmiennych

+ +
var foo = ["one", "two", "three"];
+
+var [one, two, three] = foo;
+console.log(one); // "one"
+console.log(two); // "two"
+console.log(three); // "three"
+
+ +

Przypisanie oddzielne od deklaracji

+ +

Zmiennej można przypisać wartość poprzez destrukturyzację oddzielnie od deklaracji tej zmiennej.

+ +
var a, b;
+
+[a, b] = [1, 2];
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Domyślne wartości

+ +

Zmiennej można przypisać wartość domyślną, w wypadku, gdy wartość wyciągnięta z tablicy jest niezdefiniowana - undefined.

+ +
var a, b;
+
+[a=5, b=7] = [1];
+console.log(a); // 1
+console.log(b); // 7
+
+ +

Zamiana zmiennych

+ +

Dwie zmienne mogą zamienić się miejscami przy wykorzystaniu jednego wyrażenia destrukturyzującego.

+ +

Bez wyrażenia destrukturyzującego, zamiana zmiennych wymaga zmiennej tymaczasowej (bądź, w niektórych językach niskiego poziomu, tricku XOR-swap).

+ +
var a = 1;
+var b = 3;
+
+[a, b] = [b, a];
+console.log(a); // 3
+console.log(b); // 1
+
+ +

Parsowanie tablicy zwróconej przez funkcję

+ +

Zwrócenie tablicy poprzez funkcję zawsze było możliwe. Destrukturyzacja może sprawić, że praca ze zwróconymi wartościami typu array będzie bardziej zwięzła.

+ +

W tym przykładzie, f() zwraca wartości [1, 2] jako jej wyjście, mogą one być sparsowane w jednej linijce poprzez użycie destrukturyzacji.

+ +
function f() {
+  return [1, 2];
+}
+
+var a, b;
+[a, b] = f();
+console.log(a); // 1
+console.log(b); // 2
+
+ +

Ignorowanie niektórych zwróconych wartości

+ +

Możesz zignorować zwrócone wartości, którymi nie jesteś zainteresowany.

+ +
function f() {
+  return [1, 2, 3];
+}
+
+var [a, , b] = f();
+console.log(a); // 1
+console.log(b); // 3
+
+ +

Możesz także zignorować wszystkie zwrócone wartości:

+ +
[,,] = f();
+
+ + + +

Przypisanie reszty tablicy do zmiennej

+ +

Podczas destrukturyzacji array'a możesz wypakować i przypisać jego pozostałą część do zmiennej używając operatora reszty:

+ +
var [a, ...b] = [1, 2, 3];
+console.log(a); // 1
+console.log(b); // [2, 3]
+ +

Zwróć uwagę, że zostanie wyrzucony {{jsxref("SyntaxError")}} jeśli końcowy przecinek będzie użyty z prawej strony wyrażenia z elementem reszty: 

+ +
var [a, ...b,] = [1, 2, 3];
+// SyntaxError: rest element may not have a trailing comma
+ +

Wypakowywanie wartości z wyników wyrażenia regularnego

+ +

Gdy metoda wyrażenia regularnego  exec() znajdzie pasujący element, zwraca ona tablicę zawierającą kolejno cały string zawierajacy pasujące elementy, a później elementy stringa, które pasowały do każdej grupy wyrażenia regularnego znajdującej się w nawiasach. Wyrażenie destrukturyzujące pozwala na łatwe wypakowanie elementów tej tablicy ignorując pełny string, gdy nie jest on potrzebny. 

+ +
function parseProtocol(url) {
+  var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url);
+  if (!parsedURL) {
+    return false;
+  }
+  console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"]
+
+  var [, protocol, fullhost, fullpath] = parsedURL;
+  return protocol;
+}
+
+console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"
+ +

Destrukturyzacja obiektów

+ +

Podstawowe przypisanie

+ +
var o = {p: 42, q: true};
+var {p, q} = o;
+
+console.log(p); // 42
+console.log(q); // true
+
+ +

Przypisanie bez deklaracji

+ +

Zmiennej można przypisać wartość poprzez destrukturyazację oddzielnie od deklaracji tej zmiennej.

+ +
var a, b;
+
+({a, b} = {a:1, b:2});
+ +
+

Nawiasy( .. ) na krawędziach wyrażenia przypisania są składnią wymaganą podczas używania wyrażenia destrukturyzującego literał obiektowy bez deklaracji.

+ +

{a, b} = {a:1, b:2} nie jest poprawną składnią samą w sobie, ponieważ {a, b} z lewej strony wyrażenia jest odbierana jako blok, a nie literał obiektowy.

+ +

Ale już, ({a, b} = {a:1, b:2}) jest poprawne, tak samo jak var {a, b} = {a:1, b:2}

+
+ +

Przypisanie do nowych nazw zmiennych

+ +

Zmienna może być wyciągnięta z obiektu i przypisana do zmiennej z inną nazwą niż nazwa właściwości obiektu.

+ +
var o = {p: 42, q: true};
+var {p: foo, q: bar} = o;
+
+console.log(foo); // 42
+console.log(bar); // true  
+ +

Wartości domyślne

+ +

Zmiennej można przypisać wartość domyślną, w wypadku, gdy wartość wyciągnięta z obiektu jest undefined.

+ +
var {a=10, b=5} = {a: 3};
+
+console.log(a); // 3
+console.log(b); // 5
+ + + +

Przypisywanie do nowych nazw zmiennych i zapewnienie wartości domyślnych

+ +

Właściwość może być zarówno 1) wypakowana z obiektu i przypisana do zmiennej z inną nazwą 2) może być jej przypisana wartość domyślna, gdy wypakowana wartość jest undefined.

+ +
var {a:aa = 10, b:bb = 5} = {a: 3};
+
+console.log(aa); // 3
+console.log(bb); // 5
+ + + +

Ustawianie domyślnej wartości parametru funkcji 

+ +

Wersja ES5

+ +
function drawES5Chart(options) {
+  options = options === undefined ? {} : options;
+  var size = options.size === undefined ? 'big' : options.size;
+  var cords = options.cords === undefined ? { x: 0, y: 0 } : options.cords;
+  var radius = options.radius === undefined ? 25 : options.radius;
+  console.log(size, cords, radius);
+  // now finally do some chart drawing
+}
+
+drawES5Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +

Wersja ES2015 (ES6)

+ +
function drawES2015Chart({size = 'big', cords = { x: 0, y: 0 }, radius = 25} = {}) {
+  console.log(size, cords, radius);
+  // do some chart drawing
+}
+
+// In Firefox, default values for destructuring assignments are not yet implemented (as described below).
+// The workaround is to write the parameters in the following way:
+// ({size: size = 'big', cords: cords = { x: 0, y: 0 }, radius: radius = 25} = {})
+
+drawES2015Chart({
+  cords: { x: 18, y: 30 },
+  radius: 30
+});
+ +
+

W definicji funkcji drawES2015Chart() powyżej, destrukturyzowana lewa strona wyrażenia jest przypisana do pustego literału obiektowego z prawej strony: {size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}. Można by było również napisać funkcję bez prawostronnego przypisania. Jednakże jeśli zostawisz prawą stroę przypisania, funkcja będzie szukać przynajmniej jednego argumentu podczas wywołania, natomiast w jej obecnej formie możesz po prostu wywołać drawES2015Chart() bez podawania parametrów. Ten sposób jest użyteczny gdy chcesz mieć możliwość wywołania funkcji bez podawania parametrów, ten drugi może być użyteczny, gdy chcesz być pewny, że obiekt został wprowadzony do funkcji.

+
+ +

Obiekt zagnieżdżony i destrukturyzacja tablic

+ +
var metadata = {
+    title: "Scratchpad",
+    translations: [
+       {
+        locale: "de",
+        localization_tags: [ ],
+        last_edit: "2014-04-14T08:43:37",
+        url: "/de/docs/Tools/Scratchpad",
+        title: "JavaScript-Umgebung"
+       }
+    ],
+    url: "/en-US/docs/Tools/Scratchpad"
+};
+
+var { title: englishTitle, translations: [{ title: localeTitle }] } = metadata;
+
+console.log(englishTitle); // "Scratchpad"
+console.log(localeTitle);  // "JavaScript-Umgebung"
+ +

Iteracja for..of i destrukturyzacja

+ +
var people = [
+  {
+    name: "Mike Smith",
+    family: {
+      mother: "Jane Smith",
+      father: "Harry Smith",
+      sister: "Samantha Smith"
+    },
+    age: 35
+  },
+  {
+    name: "Tom Jones",
+    family: {
+      mother: "Norah Jones",
+      father: "Richard Jones",
+      brother: "Howard Jones"
+    },
+    age: 25
+  }
+];
+
+for (var {name: n, family: { father: f } } of people) {
+  console.log("Name: " + n + ", Father: " + f);
+}
+
+// "Name: Mike Smith, Father: Harry Smith"
+// "Name: Tom Jones, Father: Richard Jones"
+ +

Wyciąganie pól z obiektów przekazanych jako parametr funkcji

+ +
function userId({id}) {
+  return id;
+}
+
+function whois({displayName, fullName: {firstName: name}}){
+  console.log(displayName + " is " + name);
+}
+
+var user = {
+  id: 42,
+  displayName: "jdoe",
+  fullName: {
+      firstName: "John",
+      lastName: "Doe"
+  }
+};
+
+console.log("userId: " + userId(user)); // "userId: 42"
+whois(user); // "jdoe is John"
+ +

To wyciąga id, displayNamefirstName z obiektu user i wypisuje je.

+ +

Wyznaczane nazwy właściwości obiektów i destrukturyzacja

+ +

Wyznaczane nazwy waściwości, tak samo jak wh literałach obiektowych, mogą być używane z destrukturyzacją.

+ +
let key = "z";
+let { [key]: foo } = { z: "bar" };
+
+console.log(foo); // "bar"
+
+ + + +

Reszta w destrukturyzacji obiektów

+ +

Własciwości reszty/rozproszenia dla ECMAScript (proponowane, etap 3) dodają składnię reszty do destrukturyzacji. Właściwości reszty zbierają pozostałe klucze, które nie zostały pobrane poprzez wzorzec destrukturyzacji.

+ +
let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
+a; // 10
+b; // 20
+rest; // { c: 30, d: 40 }
+ +

Nipoprawny identyfikator JavaScript jako nazwa własności

+ +

Destrukturyzacja może zostać użyta z nazwami własności, które nie są poprawnymi identyfikatorami JavaScript poprzez zapewnienie alternatywnego, poprawnego identyfikatora.

+ +
const foo = { 'fizz-buzz': true };
+const { 'fizz-buzz': fizzBuzz } = foo;
+
+console.log(fizzBuzz); // "true"
+ + + +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ES2015')}}Definicja wstępna.
{{SpecName('ESDraft', '#sec-destructuring-assignment', 'Destructuring assignment')}}{{Spec2('ESDraft')}}
+ +

Kompatybilność przeglądarek

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("1.8.1") }}14{{CompatNo}}{{CompatNo}}7.1
Computed property names{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}14{{CompatNo}}{{CompatNo}}{{CompatNo}}
Spread operator{{CompatChrome(49.0)}}{{ CompatGeckoDesktop("34") }}12[1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("1.0") }}{{CompatNo}}{{CompatNo}}8{{CompatChrome(49.0)}}
Computed property names{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(49.0)}}
Spread operator{{CompatNo}}{{CompatChrome(49.0)}}{{ CompatGeckoMobile("34") }}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(49.0)}}
+
+ +

[1] Wymaga odblokowanej flagi "Enable experimental Javascript features" w `about:flags`

+ +

Notatki specyficzne dla Firefox'a

+ + + +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/function/index.html b/files/pl/web/javascript/reference/operators/function/index.html new file mode 100644 index 0000000000..1d13d1a3c0 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/function/index.html @@ -0,0 +1,144 @@ +--- +title: Operator function +slug: Web/JavaScript/Referencje/Operatory/Operator_function +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/function +--- +

 

+ +

Podsumowanie

+ +

Operator function jest używany do definiowania funkcji wewnątrz wyrażenia.

+ +

Składnia

+ +
function [nazwa]([argument1[, argument2[, ..., argumentN]]]) { instrukcje }
+
+ +

Parametry

+ +
+
nazwa
+
Nazwa funkcji. Może zostać pominięta, w takim wypadku funkcja staje się anonimowa. Nazwa jest tylko lokalna i istnieje wewnętrz funkcji.
+
+ +
+
argumentN
+
Nazwa argumentu, który ma zostać przekazany do funkcji. Funkcja może posiadać do 255 argumentów.
+
+ +
+
instrukcje
+
Instrukcje, które stanowią ciało funkcji.
+
+ +

Opis

+ +

Wyrażenie funkcji jest bardzo podobne do deklaracji funkcji i posiada niemal identyczną składnię (zobacz function, aby uzyskać bardziej szczegółowe informacje). Główną różnicą pomiędzy wyrażeniem a definicją jest nazwa funkcji, która może zostać pominięta i utworzyć funkcję anonimową. Zobacz Funkcje, aby uzyskać informacje o różnicach między instrukcjami funkcji a wyrażeniami funkcji.

+ +

Przykłady

+ +

Poniższy przykład definiuje nienazwaną funkcję i przypisują ją do x. Funkcja zwraca kwadrat jej argumentów:

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

Nazwane wyrażenie

+ +
var math = {
+  'factorial': function factorial(n) {
+    if (n <= 1)
+      return 1;
+    return n * factorial(n - 1);
+  }
+};
+ +

Specyfikacja

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarze
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Zaimplementowano w JavaScript 1.5.
+ +

Wsparcie przeglądarek

+ +

{{CompatibilityTable}}

+ + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ +

Zobacz także

+ +

Funkcje, Function, Polecenie function

diff --git a/files/pl/web/javascript/reference/operators/function_star_/index.html b/files/pl/web/javascript/reference/operators/function_star_/index.html new file mode 100644 index 0000000000..52d7a67c98 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/function_star_/index.html @@ -0,0 +1,90 @@ +--- +title: wyrażenie function* +slug: Web/JavaScript/Referencje/Operatory/function* +tags: + - ECMAScript2015 + - Iterator + - JavaScript + - Operator + - funkcja +translation_of: Web/JavaScript/Reference/Operators/function* +--- +
{{jsSidebar("Operators")}}
+ +

Słowo kluczowe function* może być użyte do zdefiniowania funkcji generatora wewnątrz wyrażenia.

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

Składnia

+ +
function* [nazwa]([param1[, param2[, ..., paramN]]]) {
+   wyrażenia
+}
+ +

Parametry

+ +
+
nazwa
+
Nazw funkcji. Może być pominięta w przyadku funkcji anonimowych. Nazwa jest lokalna i ograniczona do ciała funkcji.
+
paramN
+
Nazwa argumentu przekazywanego do funkcji. Funkcja może mieć do 255 argumentów.
+
wyrażenia
+
Wyrażenia, które zawiera ciało funkcji.
+
+ +

Opis

+ +

Wyrażenie function* jest bardzo podobne i ma niemal taką samą składnię jak {{jsxref('Statements/function*', 'polecenie function*')}}. Zasadnicza różnica między wyrażenem function* a poleceniem function* to nazwa funkcji, która może być pominięta w wyrażeniach function*, co pozwala na tworzenie anonimowych funkcji generatorów. Zobacz również rozdział o funkcjach, aby dowiedzieć się więcej.

+ +

Przykłady

+ +

Następujący przykład definiuje nienazwaną funkcję generatora i przypisuje ją do x. Funkcja zwraca przekazany argument podniesiony do kwadratu.

+ +
var x = function*(y) {
+   yield y * y;
+};
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + +
SpecyfikacjaStatusKomentarz
{{SpecName('ES2015', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2015')}}Definicja początkowa.
{{SpecName('ESDraft', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ESDraft')}} 
+ +

Wsparcie przeglądarek

+ + + +

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

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/grouping/index.html b/files/pl/web/javascript/reference/operators/grouping/index.html new file mode 100644 index 0000000000..5a076c3fb0 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/grouping/index.html @@ -0,0 +1,90 @@ +--- +title: Operator grupowania +slug: Web/JavaScript/Referencje/Operatory/Grouping +tags: + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators/Grouping +--- +
{{jsSidebar("Operators")}}
+ +

Operator grupowania ( ) pozwala na określenie kolejności wykonywania działań w wyrażeniach.

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

Składnia

+ +
 ( )
+ +

Opis

+ +

Operator grupowania składa się z pary nawiasów otaczających wyrażenie lub podwyrażenie. Pozwala na nadpisanie standardowego pierwszeństwa operatorów, tak że wyrażenia z niższym piorytetem mogą być wykonane przed wyrażeniami z wyższym priorytetem. Zgodnie z nazwą, operator ten grupuje wyrażenia znajdujące się w nawiasach.

+ +

Przykłady

+ +

Nadpisanie zasady wykonywania mnożenia i dzielenia przed dodawaniem i odejmowaniem w taki sposób, by dodawanie wykonane było jako pierwsze.

+ +
var a = 1;
+var b = 2;
+var c = 3;
+
+// domyślna kolejność
+a + b * c     // 7
+// wykonywana domyślnie w taki sposób
+a + (b * c)   // 7
+
+// zmiana kolejności wykonywania działań
+// dodawanie przed mnożeniem
+(a + b) * c   // 9
+
+// co odpowiada wyrażeniu
+a * c + b * c // 9
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-grouping-operator', 'The Grouping Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.1.6', 'The Grouping Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.1.4', 'The Grouping Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
+ +

Wsparcie przeglądarek

+ + + +

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

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/in/index.html b/files/pl/web/javascript/reference/operators/in/index.html new file mode 100644 index 0000000000..0a8ef0f068 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/in/index.html @@ -0,0 +1,92 @@ +--- +title: Operator in +slug: Web/JavaScript/Referencje/Operatory/Operator_in +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/in +--- +

 

+

Podsumowanie

+

Operator in zwraca wartość true (prawda), jeśli określona własność jest w określonym obiekcie.

+ + + + + + + + + + +
Operator
Zaimplementowany w:JavaScript 1.4
+

Składnia

+

+ + propNameOrNumber + in + + objectName +

+

Parametry

+
+
+ propNameOrNumber
+
+ Łańcuch znaków lub wartość liczbowa reprezentujące nazwę własności lub indeks tablicy.
+
+
+
+ objectName
+
+ Nazwa obiektu.
+
+

Opis

+

Poniższe przykłady pokazują wybrane sposoby użycia operatora in.

+
// Tablice
+trees=new Array("redwood","bay","cedar","oak","maple")
+0 in trees        // zwraca true
+3 in trees        // zwraca true
+6 in trees        // zwraca false
+"bay" in trees    // zwraca false (musisz określić numer indeksu,
+                  // nie wartość w tym indeksie)
+"length" in trees // zwraca true (length jest własnością tablicy Array)
+
+// Obiekty predefiniowane
+"PI" in Math          // zwraca true
+myString=new String("coral")
+"length" in myString  // zwraca true
+
+// Custom objects
+mycar = {make:"Honda",model:"Accord",year:1998}
+"make" in mycar  // zwraca true
+"model" in mycar // zwraca true
+
+

Musisz określić obiekt z prawej strony operatora in. Na przykład: możesz określić łańcuch znaków stworzony za pomocą konstruktora String, ale nie możesz określić łańcucha znaków wprost.

+
color1=new String("green")
+"length" in color1 // zwraca true
+color2="coral"
+"length" in color2 // generuje błąd (color nie jest obiektem typu String)
+
+

Zastosowanie in z usuniętymi lub niezdefiniowanymi własnościami

+

Jeśli usuniesz własność za pomocą operatora delete, operator in zwróci wartość false (fałsz) dla tej własności.

+
mycar = {make:"Honda",model:"Accord",year:1998}
+delete mycar.make
+"make" in mycar  // zwraca false
+
+trees=new Array("redwood","bay","cedar","oak","maple")
+delete trees[3]
+3 in trees // zwraca false
+
+

Jeśli ustalisz własność jako niezdefiniowaną, ale nie usuniesz jej, operator in zwróci wartość true (prawda) dla tej własności.

+
mycar = {make:"Honda",model:"Accord",year:1998}
+mycar.make=undefined
+"make" in mycar  // zwraca true
+
+trees=new Array("redwood","bay","cedar","oak","maple")
+trees[3]=undefined
+3 in trees // zwraca true
+
+

Aby uzyskać dodatkowe informacje o zastosowaniu operatora in z usuniętymi elementami tablicy, zobacz delete.

diff --git a/files/pl/web/javascript/reference/operators/index.html b/files/pl/web/javascript/reference/operators/index.html new file mode 100644 index 0000000000..016c55af35 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/index.html @@ -0,0 +1,282 @@ +--- +title: Operatory +slug: Web/JavaScript/Referencje/Operatory +tags: + - JavaScript + - Operators +translation_of: Web/JavaScript/Reference/Operators +--- +
{{jsSidebar("Operators")}}
+ +

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

+ +

Wyrażenia i operatory w podziale na  kategorie

+ +

 

+ +

Lista operatorów w kolejności alfabetycznej znajduje sie w pasku bocznym po lewej stronie.

+ +

Wyrażenia podstawowe

+ +

Podstawowe słowa kluczowe i wyrażenia w  JavaScript.

+ +
+
{{jsxref("Operator/this", "this")}}
+
Słowo this odnosi się do kontekstu wywołania.
+
{{jsxref("Operator/function", "function")}}
+
Słowo function umożliwia zdefniowanie wyrażenia funkcji .
+
{{experimental_inline}} {{jsxref("Operatory/class", "class")}}
+
Słowo class definiuje wyrażenie klasy.
+
{{experimental_inline}} {{jsxref("Operatory/function*", "function*")}}
+
The function* keyword defines a generator function expression.
+
{{experimental_inline}} {{jsxref("Operatory/yield", "yield")}}
+
Pause and resume a generator function
+
{{experimental_inline}} {{jsxref("Operatory/yield*", "yield*")}}
+
Delegate to another generator function or iterable object.
+
{{jsxref("Global_Objecty/Array", "[]")}}
+
Array initializer/literal syntax.
+
{{jsxref("Operatory/Object_initializer", "{}")}}
+
Object initializer/literal syntax.
+
{{jsxref("RegExp", "/ab+c/i")}}
+
Regular expression literal syntax.
+
{{experimental_inline}} {{jsxref("Operatory/Array_comprehensions", "[for (x of y) x]")}}
+
Array comprehensions.
+
{{experimental_inline}} {{jsxref("Operatory/Generator_comprehensions", "(for (x of y) y)")}}
+
Generator comprehensions.
+
{{jsxref("Operatory/Grouping", "( )")}}
+
Grouping operator.
+
+ +

Left-hand-side expressions

+ +

Left values are the destination of an assignment.

+ +
+
{{jsxref("Operatory/Property_accessors", "Property accessors", "", 1)}}
+
Member operators provide access to a property or method of an object
+ (object.property and object["property"]).
+
{{jsxref("Operatory/new", "new")}}
+
The new operator creates an instance of a constructor.
+
{{experimental_inline}} {{jsxref("Operatory/super", "super")}}
+
The super keyword calls the parent constructor.
+
{{experimental_inline}} {{jsxref("Operatory/Spread_operator", "...obj")}}
+
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
+
+ +

Increment and decrement

+ +

Postfix/prefix increment and postfix/prefix decrement operators.

+ +
+
{{jsxref("Operatory/Operatory_arytmetyczne", "A++", "#Inkrementacja")}}
+
Postfix increment operator.
+
{{jsxref("Operatory/Operatory_arytmetyczne", "A--", "#Dekrementacja")}}
+
Postfix decrement operator.
+
{{jsxref("Operatory/Operatory_arytmetyczne", "++A", "#Inkrementacja")}}
+
Prefix increment operator.
+
{{jsxref("Operatory/Operatory_arytmetyczne", "--A", "#Dekrementacja")}}
+
Prefix decrement operator.
+
+ +

Unary operators

+ +

A unary operation is operation with only one operand.

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

Operatory arytmetyczne

+ +

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

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

Operatory porównania

+ +

Operator porównania, jak nazwa wskazuje, porównuje operandy  i zwraca wartość logiczną zależną od tego, czy wartość porównania jest prawdziwa. 

+ +
+
{{jsxref("Operatory/in", "in")}}
+
Operator in ustala, czy obiekt posiada daną właściwość.
+
{{jsxref("Operatory/instanceof", "instanceof")}}
+
Operator instanceof ustala czy obiekt jest instancją innego obiektu.
+
{{jsxref("Operatory/Comparison_Operators", "<", "#Less_than_operator")}}
+
Less than operator.
+
{{jsxref("Operatory/Comparison_Operators", ">", "#Greater_than_operator")}}
+
Greater than operator.
+
{{jsxref("Operatory/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
+
Less than or equal operator.
+
{{jsxref("Operatory/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
+
Greater than or equal operator.
+
+ +

Equality operators

+ +

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

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

Bitwise shift operators

+ +

Operations to shift all bits of the operand.

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

Binary bitwise operators

+ +

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

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

Binary logical operators

+ +

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

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

Conditional (ternary) operator

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

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

+
+
+ +

Assignment operators

+ +

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

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

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

+
+
+ +

Comma operator

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

Non-standard features

+ +
+
{{non-standard_inline}} {{jsxref("Operatory/Legacy_generator_function", "Legacy generator function", "", 1)}}
+
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
+
{{non-standard_inline}} {{jsxref("Operatory/Expression_closures", "Expression closures", "", 1)}}
+
The expression closure syntax is a shorthand for writing simple function.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition.
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword, Array comprehensions, Generator comprehensions
+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/operators/instanceof/index.html b/files/pl/web/javascript/reference/operators/instanceof/index.html new file mode 100644 index 0000000000..d9b83cd838 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/instanceof/index.html @@ -0,0 +1,168 @@ +--- +title: Operator instanceof +slug: Web/JavaScript/Referencje/Operatory/Operator_instanceof +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Strony_wymagające_dopracowania + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/instanceof +--- +
{{jsSidebar("Operators")}}
+ +

Operator instanceof sprawdza czy właściwość konstruktora prototype pojawia się gdziekolwiek w łańcuchu prototypowym obiektu.

+ +

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

+ + + +

Składnia

+ +
object instanceof constructor
+ +
+
+

Parametry

+ object
+
Obiekt do testowania.
+
+ +
+
constructor
+
Funkcja przeciwko której testujemy.
+
+ +

Opis

+ +

Operator instanceof sprawdza obecność constructor.prototype w łańcuchu prototypowym obiektu object

+ +
// definiowanie konstruktorów
+function C() {}
+function D() {}
+
+var o = new C();
+
+// true, ponieważ: Object.getPrototypeOf(o) === C.prototype
+o instanceof C;
+
+// false, ponieważ D.prototype nie występuje w łańcuchu prototypowym o.
+o instanceof D;
+
+o instanceof Object; // true, ponieważ:
+C.prototype instanceof Object // true
+
+C.prototype = {};
+var o2 = new C();
+
+o2 instanceof C; // true
+
+// false, ponieważ C.prototype nie ma już w łańcuchu prototypowym o
+o instanceof C;
+
+D.prototype = new C(); // add C to [[Prototype]] linkage of D
+var o3 = new D();
+o3 instanceof D; // true
+o3 instanceof C; // true since C.prototype is now in o3's prototype chain
+
+ +

Note that the value of an instanceof test can change based on changes to the prototype property of constructors, and it can also be changed by changing an object prototype using Object.setPrototypeOf. It is also possible using the non-standard __proto__ pseudo-property.

+ +

instanceof and multiple context (e.g. frames or windows)

+ +

Different scopes have different execution environments. This means that they have different built-ins (different global object, different constructors, etc.). This may result in unexpected results. For instance, [] instanceof window.frames[0].Array will return false, because Array.prototype !== window.frames[0].Array and arrays inherit from the former.

+ +

This may not make sense at first but when you start dealing with multiple frames or windows in your script and pass objects from one context to another via functions, this will be a valid and strong issue. For instance, you can securely check if a given object is, in fact, an Array using Array.isArray(myObj)

+ +

For example checking if a Nodes is a SVGElement in a different context you can use myNode instanceof myNode.ownerDocument.defaultView.SVGElement

+ +
Note for Mozilla developers:
+In code using XPCOM instanceof has special effect: obj instanceof xpcomInterface (e.g. Components.interfaces.nsIFile) calls obj.QueryInterface(xpcomInterface) and returns true if QueryInterface succeeded. A side effect of such call is that you can use xpcomInterface's properties on obj after a successful instanceof test. Unlike standard JavaScript globals, the test obj instanceof xpcomInterface works as expected even if obj is from a different scope.
+ +

Examples

+ +

Demonstrating that String and Date are of type Object and exceptional cases

+ +

The following code uses instanceof to demonstrate that String and Date objects are also of type Object (they are derived from Object).

+ +

However, objects created with the object literal notation are an exception here: Although the prototype is undefined, instanceof Object returns true.

+ +
var simpleStr = 'This is a simple string';
+var myString  = new String();
+var newStr    = new String('String created with constructor');
+var myDate    = new Date();
+var myObj     = {};
+
+simpleStr instanceof String; // returns false, checks the prototype chain, finds undefined
+myString  instanceof String; // returns true
+newStr    instanceof String; // returns true
+myString  instanceof Object; // returns true
+
+myObj instanceof Object;    // returns true, despite an undefined prototype
+({})  instanceof Object;    // returns true, same case as above
+
+myString instanceof Date;   // returns false
+
+myDate instanceof Date;     // returns true
+myDate instanceof Object;   // returns true
+myDate instanceof String;   // returns false
+
+ +

Demonstrating that mycar is of type Car and type Object

+ +

The following code creates an object type Car and an instance of that object type, mycar. The instanceof operator demonstrates that the mycar object is of type Car and of type Object.

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+var mycar = new Car('Honda', 'Accord', 1998);
+var a = mycar instanceof Car;    // returns true
+var b = mycar instanceof Object; // returns true
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-relational-operators', 'Relational Operators')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-11.8.6', 'The instanceof operator')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.4.
+ +

Browser compatibility

+ + + +

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

+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/operators/new.target/index.html b/files/pl/web/javascript/reference/operators/new.target/index.html new file mode 100644 index 0000000000..8b60074e92 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/new.target/index.html @@ -0,0 +1,134 @@ +--- +title: new.target +slug: Web/JavaScript/Referencje/Operatory/new.target +translation_of: Web/JavaScript/Reference/Operators/new.target +--- +
{{JSSidebar("Operators")}}
+ +

new.target pozwala sprawdzić czy konstruktor lub funkcja była zainicjalizowana używając operatora new. Kiedy w konstruktorze lub funkcji zainicjalizowany jest operatora new, new.target zwraca referencje do konstruktora lub funkcji. W normalnym wywołaniu funkcji, new.target jest {{jsxref("undefined")}}.

+ +

Syntax

+ +
new.target
+ +

Opis

+ +

new.target składa się ze słowa "new", kropki i pola o nazwie "target". Przeważnie "new." jest kontekstem dostępu do pola, ale w tym przypadku "new." nie jest tak naprawdę obiektem. W wywołaniu konstruktora, new.target nawiązuje do konstruktora wywołanego przez new więc "new." staje się wirtualnym kontekstem.

+ +

Pole new.target jest meta polem które jest dostępne dla wszystkich funkcji. W arrow functions, new.target nawiązuje do new.target otaczającej funkcji.

+ +

Przykłady

+ +

new.target w wywołaniu funkcji

+ +

W normalnym wywołaniu funkcji (w przeciwieństwie do wywołania konstruktora), new.target jest {{jsxref("undefined")}}. Pozwala Ci to stwierdzić, czy funkcja została wywołana wraz z new jako konstruktor.

+ +
function Foo() {
+  if (!new.target) throw "Foo() must be called with new";
+  console.log("Foo instantiated with new");
+}
+
+Foo(); // throws "Foo() must be called with new"
+new Foo(); // logs "Foo instantiated with new"
+
+ +

new.target w konstruktorze

+ +

W konstruktorach klasy, new.target nawiązuje do konstruktora który został bezpośrednio wywołany z new. Dzieje się tak również w przypadku kiedy konstruktor znajduje się w klasie rodzica, i został wywołany z konstruktorze dziecka.

+ +
class A {
+  constructor() {
+    console.log(new.target.name);
+  }
+}
+
+class B extends A { constructor() { super(); } }
+
+var a = new A(); // logs "A"
+var b = new B(); // logs "B"
+
+ +

Specyfikacja

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-built-in-function-objects', 'Built-in Function Objects')}}{{Spec2('ESDraft')}} 
+ +

Kompatybilność przeglądarek

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(46.0)}}{{CompatGeckoDesktop(41)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatChrome(46.0)}}{{CompatGeckoMobile(41)}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(46.0)}}
+
+ +

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/operators/new/index.html b/files/pl/web/javascript/reference/operators/new/index.html new file mode 100644 index 0000000000..e6153d3a69 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/new/index.html @@ -0,0 +1,183 @@ +--- +title: Operator new +slug: Web/JavaScript/Referencje/Operatory/Operator_new +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Strony_wymagające_dopracowania + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/new +--- +
{{jsSidebar("Operators")}}
+ +

Operator new tworzy nową instancję typu obiektu zdenifiowanego przez użytkownika lub instancję wbudowanego typu obiektu, który posiada konstruktor.

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

Składnia

+ +
new constructor[([arguments])]
+ +

Parametry

+ +
+
constructor
+
Klasa bądź funkcja, która definiuje typ obiektu instancji.
+
+ +
+
arguments
+
Lista wartości z którymi zostanie wywołany constructor.
+
+ +

Opis

+ +

Tworzenie obiektu przez zdefiniowanego przez użytkownika przebiega w dwóch krokach:

+ +
    +
  1. Zdefiniowanie typu obiektu poprzez napisanie funkcji.
  2. +
  3. Tworzenie jego instancji przy użyciu słowa kluczowego new.
  4. +
+ +

Aby zdefiniować typ obiektu, stwórz funkcję dla tego typu, która określa jego nazwę i właściwości. Obiekt może mieć właściwość, której wartością jest on sam lub inny obiekt. Spójrz na przykłady poniżej

+ +

Kiedy wykonywaniy jest kod new Foo(...), dzieją się następujące rzeczy:

+ +
    +
  1. Tworzeny jest nowy obiekt, dzidziczący po Foo.prototype.
  2. +
  3. Wywoływany jest konstruktor Foo z określonymi argumentami, a kontekst this zostaje przypisany do nowo utworzonego obiektu. new Foo jest równoznaczne z new Foo(), tzn. w przypadku gdy lista argumentów jst nieokreślona, Foo jest wywoływane bez argumentów.
  4. +
  5. Obiekt zwrócony przez konstruktor staje się wynikiem całego wyrażenia new. Jeżeli konstruktor nie zwraca obiektu, obiekt stworzony w kroku 1 jest używany zamiast niego. (Zwykle kontruktory nie zwracają żadnej wartości, ale mogą tak czynić jeśli chcą nadpiać normalny proces tworzenia obiektu.)
  6. +
+ +

Zawsze można dodać właściwość do wcześniej stworzonego obiektu. Na przykład, wyrażenie car1.color = "black" dodaje właściwość color do car1, przypisuje mu wartość "black". Jednakże, nie wpływa to w żaden sposób na inne obiekty. Aby dodać właściwość do wszystkich obiektów tego samego typu, trzeba dodać tę właściwość do definicji typu obiektu Car.

+ +

Można dodać wspólną właściwość do wcześniej zdefiniowanego typu obiektu korzystając z właściwości Function.prototype. Definiuje ona wspólną właściwość dla wszystkich obiektów tego typu, a nie charakterystyczną dla instancji typu obiektu. Następujący kod dodaje właściwość color o wartości null do wszystkich obiektów typu Car, a następnie znienia tę wartość tylko w obiekcie car1 na łańcuch "black" . Po więcej informacji, zobacz prototype.

+ +
function Car() {}
+car1 = new Car();
+
+console.log(car1.color);    // undefined
+
+Car.prototype.color = null;
+console.log(car1.color);    // null
+
+car1.color = 'black';
+console.log(car1.color);   // black
+
+ +

Przykłady

+ +

Typ obiektu i jego instancja

+ +

Przypuśćmy, że chcesz stworzyś typ obiektu dla aut. Chcesz, żeby był nazwany car i by miał właściwości makemodel i year. Żeby to osiągnąć należy stworzyć następującą funkcję:

+ +
function Car(make, model, year) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+}
+
+ +

Teraz można stworzyć obiekt mycar:

+ +
var mycar = new Car('Eagle', 'Talon TSi', 1993);
+
+ +

Powyższy kod deklaruje zmienną mycar i przypisuje do niej określone właściwości. Wartość mycar.make to łańcuch "Eagle", mycar.year to liczba 1993 itd.

+ +

Można stworzyć nieograniczoną ilość obiektów Car poprzez słowo kluczowe new. Na przykład:

+ +
var kenscar = new Car('Nissan', '300ZX', 1992);
+
+ +

Właściwość obiektu, będąca innym obiektem

+ +

Przypuśćmy, że definiujemy typ obiektu Person jak poniżej:

+ +
function Person(name, age, sex) {
+  this.name = name;
+  this.age = age;
+  this.sex = sex;
+}
+
+ +

A następnie tworzymy dwa obiekty Person:

+ +
var rand = new Person('Rand McNally', 33, 'M');
+var ken = new Person('Ken Jones', 39, 'M');
+
+ +

Teraz możemy przepisać definicję Car tak, by zawierała właściwość owner, która przyjmuje obiekt:

+ +
function Car(make, model, year, owner) {
+  this.make = make;
+  this.model = model;
+  this.year = year;
+  this.owner = owner;
+}
+
+ +

Aby utworzyć nowe obiekty, należy napisać:

+ +
var car1 = new Car('Eagle', 'Talon TSi', 1993, rand);
+var car2 = new Car('Nissan', '300ZX', 1992, ken);
+
+ +

Zamiast przekazywania wartości liczbowych lub łańcuchów znaków, w powyższym przykładzie przekazywane są obiekty: rand oraz ken. Aby uzyskać imię właściciela samochodu car2, należy napisać:

+ +
car2.owner.name
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecifikacjaStatusKomentarz
{{SpecName('ESDraft', '#sec-new-operator', 'The new Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-new-operator', 'The new Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.2.2', 'The new Operator')}}{{Spec2('ES1')}}Wstępna definicja. Zaimpelementowano w JavaScript 1.0.
+ +

Wsparcie przeglądarek

+ + + +

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

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/pl/web/javascript/reference/operators/nullish_coalescing_operator/index.html new file mode 100644 index 0000000000..c8a264e50e --- /dev/null +++ b/files/pl/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -0,0 +1,251 @@ +--- +title: Operator null'owego scalania (??) +slug: Web/JavaScript/Referencje/Operatory/Nullish_coalescing_operator +tags: + - JavaScript + - Language feature + - Operator + - Reference + - nullish coalescing +translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator +--- +

{{JSSidebar("Operators")}}

+ +

Operator null'owego scalania (??) - to operator logiczny, stosowany w wyrażeniach, który zwraca to co jest po jego lewej stronie, tak długo, jak to nie jest null, albo undefined, wtedy zwraca to, co jest po prawej.

+ +
+

Początkowo ewaluowane jest tylko wyrażenie z lewej strony.
+ Dopiero, gdy zachodzi taka potrzeba, ewaluowane jest prawe wyrażenie.

+
+ +

Jest podobny do logicznego operatora LUB (||)Logical OR (||) ), ale LUB decyduje o tym, czy wziąć prawą wartość, na innej podstawie:
+ Czy lewa wartość jest fałszopodobna (Falsy)?
+ null i undefined są fałszopodobne, ale sęk w tym, że nie tylko one, ale również np. 0, czy "". Czasem nie chce się podmieniać niczego za 0 i "", uważając je za dopuszczalne wartości.
+ Wtedy właśnie przydaje się ten operator.

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

Składnia

+ +
LWyr ?? PWyr
+ + + + + + + + + + + + + + + + + + +
PoleOpis
LWyrWyrażenie główne, ewaluowane na początku.
+ Jeżeli jego wartość wynikowa jest null, albo undefined, to nie ona zostanie zwrócona, ale wartość wynikowa wyrażenia PWyr
PWyrWyrażenie zamienne, ewaluowane, kiedy wartość LWyr jest null, albo undefined.
+ +

Przykłady

+ +

Użycie operatora

+ +

W tym przykładzie użyjemy operatora null'owego scalania do podania zapasowych wartości, przy inicjowaniu stałych:

+ +
const wartoscNull = null;
+const warA = wartoscNull ?? "domyślne dla A";
+console.log(warA);
+
+// konsola: "domyślne dla A"
+
+
+
+const pustyTekst = "";   // fałszopodobny
+const warB = pustyTekst ?? "domyślne dla B";
+console.log(warB);
+
+// konsola: ""
+// ponieważ "??" reaguje tylko konkretnie na null albo undefined
+
+
+
+const jakasLiczba = 42;
+const warC = jakasLiczba ?? 0;
+console.log(warC);
+
+// konsola: 42
+ +

Porównanie działania "??" i "||"

+ +

Wcześniej przed pojawieniem się tego operatora, używano LUB (||) (Logical OR (||)):

+ +
let liczba;
+let zabezpLicz = liczba || 1;
+// zmienna "wejscie" nie była nigdy zapełniona żadną wartością,
+// więc była "undefined", a undefined jest fałszopodobne, więc
+// JavaScript wziął zapasowe '1'.
+
+console.log(2 * zabezpLicz);
+// konsola: 2
+
+ +

To działa, ale...
+ przez to jakim operatorem jest LUB, nie tylko undefined zostanie tu zamienione, ale też i 0, które, w kontekście tego przykładu, powiedzmy, że jest wartością, która powinna być ok:

+ +
let liczba = 0;
+let zabezpLicz = liczba || 1;
+// zmienna "wejscie" została zapełniona zerem, ale jest fałszopodobne,
+//więc JavaScript wziął zapasowe '1'.
+
+console.log(2 * zabezpLicz);
+// konsola: 2
+// chcieliśmy: 0
+
+ +

Operator null'owego scalania rozwiązuje ten problem:

+ +
let liczba = 0;
+let zabezpLicz = liczba ?? 1;
+// zmienna "wejscie" została zapełniona zerem,
+//mimo tego, że jest fałszopodobne, "??" akceptuje je, bo to nie null, ani undefined, i
+//JavaScript zostawia '0'.
+
+console.log(2 * zabezpLicz);
+// konsola: 0
+
+ +

Pomijanie ewaluacji

+ +

Podobnie jak inne operatory logiczne LUB (Logical OR (||)) i I (Logical AND (&&)), ten operator rozpoczyna od ewaluacji wyrażenia po lewej stronie, i dopiero gdy trzeba, zajmuje się prawą stroną:

+ +
function A(){
+  console.log("Tu A!");
+  return false;
+}
+function B(){
+  console.log("Tu B!");
+  return true;
+}
+
+if( A() ?? B() ) console.log("Otrzymano 'true'");
+else console.log("Otrzymano 'false'");
+// konsola: "Otrzymano 'false'"
+
+ +

i :

+ +
function A(){
+  console.log("Tu A!");
+  return null; // teraz tu jest zwracany null, na który reaguje "??"
+}
+function B(){
+  console.log("Tu B!");
+  return true;
+}
+
+if( A() ?? B() ) console.log("Otrzymano 'true'");
+else console.log("Otrzymano 'false'");
+// konsola: "Otrzymano 'true'"
+ +

Nie działa seryjnie, ani z LUB, ani z I

+ +

W wyrażeniach, nie można stawiać zwyczajnie operatora null'owego scalania w otoczeniu operatorów LUB i I, mimo ustalonej kolejności wykonywania działań. Będzie to odbierane jako błąd składniowy:

+ +
null || undefined ?? "yyy..."; // to będzie SyntaxError
+true || undefined ?? "aha.";   // to też będzie SyntaxError
+//bo tu chodzi o to, że jest "||" i "??" razem, nie o wartości.
+
+ +

Trzeba je rozdzielić nawiasami:

+ +
(null || undefined) ?? "yyy...";  // zwraca: "yyy..."
+null || (undefined ?? "działa!"); // zwraca: "działa!"
+
+ +

Odniesienie do Operatora opcjonalnego dostępu "?."

+ +

Sposób w który operator null'owego scalania pracuje z wartościami null i undefined, jest intuicyjny analogicznie u operatora opcjonalnego dostępu (Optional chaining (?.), i razem pozwalają na ciekawe akcje, np.:

+ +
class objekt{
+  tekst;
+
+  constructor(tekst = null){
+    this.tekst = tekst;
+  }
+
+  odczytTekst(){
+    return this.tekst;
+  }
+  wpisTekst(w){
+    this.tekst = w;
+    return true;
+  }
+}
+
+let objekty = [new objekt("cześć!"), null, new objekt()];
+
+
+
+// zadanie kodu: zamień tekst'y w objekt'ach na duże litery,
+// używając funkcji dostępu, a pozostawiając puste wartości
+// bez zmian
+
+
+// wersja typeof
+for(let i = 0; i < objekty.length; i++)
+  if(typeof(objekty[i]) == "object")
+    if(typeof(objekty[i].odczytTekst()) == "string")
+      objekty[i].wpisTekst(objekty[i].odczytTekst().toUpperCase());
+
+
+// wersja operatorów "??" i "?."
+for(let i = 0; i < objekty.length; i++)
+  objekty[i]?.wpisTekst(objekty[i]?.odczytTekst()?.toUpperCase() ?? null);
+
+console.log(objekty);
+
+ +

Czasami użycie tych operatorów upraszcza kod.
+ Poza tym każda funkcja jest wywoływana najwyżej raz i może to być co kolwiek.

+ +

Specyfikacje

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#prod-Nulli', 'nullish coalescing expression')}}
+ +

Wsparcie przeglądarek

+ + + +

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

+ +

Postępy implementacji

+ +

Tabelka pod spodem pokazuje codzienny status implementacji tej funkcji. Jest tak, ponieważ nie osiągnięto jeszcze stabilności między przeglądarkami.
+ Dane są generowane, poprzez przeprowadzanie odpowiednich testów funkcji w Test262, standardowym zestawie testów dla JavaScripta, na najnowszych kompilacjach (en: "nightly build"), lub najnowszych wydaniach (en: "latest release") silników JavaScripta przeglądarek.

+ +
{{EmbedTest262ReportResultsTable("coalesce-expression")}}
+ +

Zobacz też...

+ + diff --git a/files/pl/web/javascript/reference/operators/object_initializer/index.html b/files/pl/web/javascript/reference/operators/object_initializer/index.html new file mode 100644 index 0000000000..4148cc07d1 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/object_initializer/index.html @@ -0,0 +1,387 @@ +--- +title: Inicjalizator obiektu +slug: Web/JavaScript/Referencje/Operatory/Object_initializer +translation_of: Web/JavaScript/Reference/Operators/Object_initializer +--- +
{{JsSidebar("Operators")}}
+ +

Obiekty można tworzyć używając new Object(), Object.create(), bądź wykorzystując notację literałową (notację inicializacyjną). Inicjalizator obiektu to lista zera lub więcej par - nazw właściwości oraz ich wartości - otoczonych nawiasami klamrowymi ({}).

+ +

Składnia

+ +
var o = {};
+var o = { a: "foo", b: 42, c: {} };
+
+var a = "foo", b = 42, c = {};
+var o = { a: a, b: b, c: c };
+
+var o =
+{
+  wlasciwosc: function ([parametry]) {},
+  get wlasciwosc() {},
+  set wlasciwosc(wartosc) {},
+};
+
+ +

Nowe notacje w ECMAScript 2015

+ +

Pamiętaj aby zapoznać się z tabelą kompatybilności. Środowiska nie obsługujące tych notacji będą wyrzucać błędy składni.

+ +
// Skrótowe nazwy właściwości (ES6)
+var a = "foo", b = 42, c = {};
+var o = { a, b, c };
+
+// Skrótowe nazwy metod (ES6)
+var o = {
+  wlasciwosc([parametry]) {},
+  get wlasciwosc() {},
+  set wlasciwosc(wartosc) {},
+  * generator() {}
+};
+
+// Obliczone nazwy właściwości (ES6)
+var nazwa = "foo";
+var o = {
+  [nazwa]: "dzien",
+  ["b" + "ar"]: "dobry",
+};
+ +

Opis

+ +

Inicjalizator obiektu to wyrażenie opisujące inicjalizację obiektu {{jsxref("Object")}}. Obiekty składają się z właściwości używanych do opisywania obiektu. Wartości tych właściwości mogą zawierać {{Glossary("primitive")}} typy danych albo inne obiekty.

+ +

Tworzenie obiektów

+ +

Pusty obiekt możemy stworzyć w taki sposób:

+ +
var obiekt = {};
+ +

Jednak prawdziwą przewagą notacji literałowej jest możliwość tworzenia w szybki sposób obiektów ze zdefiniowanymi od razu właściwościami. Wystarczy wypisać listę kluczy: wartości odzdzielonych dwukropkiem. Poniższy przykład tworzy obiekt osoba z trzema właściwościami: "imie", "wiek" i "wyglad". Ich wartościami jest string "Adam", numer 42 oraz inny obiekt.

+ +
var osoba =
+{
+  imie: "Adam",
+  wiek: 42,
+  wyglad: { wzrost: 179 },
+}
+ +

Dostęp do właściwości

+ +

Kiedy już stworzyłeś obiekt, możesz chcieć zobaczyć lub zmienić jego właściwości. Można zrobić to używając zapisu z kropką lub nawiasami. Zajrzyj do operatorów pamięci po więcej informacji.

+ +
object.imie; // "Adam"
+object["wiek"]; // 42
+
+object.imie = "Ewa";
+
+ +

Definiowanie właściwości

+ +

Nauczyliśmy się już jak zapisywać właściwości używając notacji literałowej. Czasami jednak mamy w kodzie zmienne, które chcielibyśmy dodać do naszego obiektu. Możemy to zrobić w taki sposób:

+ +
var a = "foo",
+    b = 42,
+    c = {};
+
+var o =
+{
+  a: a,
+  b: b,
+  c: c
+};
+ +

Ale ECMAScript 2015 oddaje nam do dyspozycji krótszy zapis, pozwalający uzyskać ten sam efekt:

+ +
var a = "foo",
+    b = 42,
+    c = {};
+
+// Skrótowe nazwy właściwości (ES6)
+var o = { a, b, c };
+ +

Duplikowanie nazw właściwości

+ +

W momencie, gdy użyjemy już istniejącej nazwy właściwości jej wartość nadpisze tę poprzednią.

+ +
var a = {x: 1, x: 2};
+console.log(a); // { x: 2}
+
+ +

W ECMAScript 5 strict mode, duplikowanie nazw właściwości było postrzegane jako {{jsxref("SyntaxError")}}. Zmieniono to jednak po wprowadzeniu obliczanych nazw właściwości. Duplikacja stała się wówczas możliwa podczas wykonywania kodu, dlatego też w ECMAScript 2015 usunięto tę rystrykcję.

+ +
function czyES6UmozliwiaDuplikowanieWlasciwosci()
+{
+  "use strict";
+  try
+  {
+    ({ prop: 1, prop: 2 });
+
+    // Nie wyrzucono błędu, duplikacja dozwolona w strict mode.
+    return true;
+  }
+  catch (e)
+  {
+    // Wyrzucono błąd, duplikacja w strict mode zabroniona.
+    return false;
+  }
+}
+ +

Definicje metod

+ +

Właściwość obiektu może również odnosić się do funkcji albo metody getter lub setter.

+ +
var o = {
+  wlasciwos: function ([parametry]) {},
+  get wlasciwos() {},
+  set wlasciwos(wartosc) {},
+};
+ +

w ECMAScript 2015, mamy dostęp do skróconego zapisu, takiego w którym słowo kluczowe "function" nie jest nam już potrzebne.

+ +
// Shorthand method names (ES6)
+var o = {
+  property([parameters]) {},
+  get property() {},
+  set property(value) {},
+  * generator() {}
+};
+ +

W ECMAScript 2015 możemy również w prostszy sposób zapisać właściwość będącą funkcją generatora:

+ +
var o = {
+  * generator() {
+    ...........
+  }
+};
+ +

W ECMAScript 5 musielibyśmy zapisać to tak (aczkolwiek pamiętaj że w ES5 nie ma generatorów):

+ +
var o = {
+  generator: function *() {
+    ...........
+  }
+};
+ +

Po więcej informacji zajrzyj do definicji metod.

+ +

Obliczone nazwy właściwości

+ +

Od ECMAScript 2015, składnia inicjalizatora obiektu wspiera także obliczone nazwy właściwości. Umożliwia to umieszczenie wyrażenia w nawiasach [], które potem zostanie przeliczone na nazwę właściwości. Działa to na tej samej zasadzie co zapis klamrowy w operatorach pamięci, z którymi zapewne miałeś już styczność. Teraz możemy użwać tej samej składni w notacji literałowej:

+ +
// Obliczone nazwy właściwości (ES6)
+var i = 0;
+var a = {
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i,
+  ["foo" + ++i]: i
+};
+
+console.log(a.foo1); // 1
+console.log(a.foo2); // 2
+console.log(a.foo3); // 3
+
+var param = 'typ';
+var info = {
+  [param]: 'strona',
+  ["pod" + param.charAt(0).toUpperCase() + param.slice(1)]: 'forum'
+};
+
+console.log(info); // { typ: 'strona', 'podTyp': 'forum' }
+ +

Zmiana prototypu

+ +

Definicja właściwości w formie __proto__: wartosc albo "__proto__": wartosc nie stworzy właściwości z nazwą __proto__. Zamiast tego, jeżeli podana wartość jest obiektem lub typem null, zamieni ona [[Prototype]] tworzonego obiektu na podaną wartość. (Jeżeli wartość nie jest ani obiektem ani typem null prototyp nie zostanie zmieniony.)

+ +
var obj1 = {};
+console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
+
+var obj2 = { __proto__: null };
+console.log(Object.getPrototypeOf(obj2) === null); // true
+
+var protoObj = {};
+var obj3 = { "__proto__": protoObj };
+console.log(Object.getPrototypeOf(obj3) === protoObj); // true
+
+var obj4 = { __proto__: "not an object or null" };
+console.log(Object.getPrototypeOf(obj4) === Object.prototype); // true
+console.log(!obj4.hasOwnProperty("__proto__")); // true
+
+ +

Podczas notacji literałowej możemy zmienić prototyp tylko raz, kolejne próby będą skutkować błędami składni.

+ +

Jeżeli użyjemy w defninicji nazwy __proto__ bez używania składni z dwukropkiem, nazwa ta będzie się zachowywać jak kazda inna.

+ +
var __proto__ = "wartosc";
+
+var obj1 = { __proto__ };
+console.log(Object.getPrototypeOf(obj1) === Object.prototype); // true
+console.log(obj1.hasOwnProperty("__proto__")); // true
+console.log(obj1.__proto__ === "wartosc"); // true
+
+var obj2 = { __proto__() { return "witaj"; } };
+console.log(obj2.__proto__() === "witaj"); // true
+
+var obj3 = { ["__prot" + "o__"]: 17 };
+console.log(obj3.__proto__ === 17); // true
+
+ +

Notacja literałowa vs JSON

+ +

Notacja literałowa to nie to samo co JavaScript Object Notation (JSON). Pomimo, że wyglądają podobnie, są miedzy nimi poważne różnice:

+ + + +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Początkowa definicja.
{{SpecName('ES5.1', '#sec-11.1.5', 'Object Initializer')}}{{Spec2('ES5.1')}}Dodano metody getter oraz setter.
{{SpecName('ES6', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ES6')}}Skrócone nazwy właściwości/metod oraz obliczone nazwy właściwości.
{{SpecName('ESDraft', '#sec-object-initializer', 'Object Initializer')}}{{Spec2('ESDraft')}} 
+ +

Kompatybilność z przeglądarkami

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(1.0)}}{{CompatGeckoDesktop("1.0")}}111
Computed property names{{CompatVersionUnknown}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatNo}}7.1
Shorthand property names{{CompatVersionUnknown}}{{CompatGeckoDesktop("33")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Shorthand method names{{CompatChrome(42.0)}}{{CompatGeckoDesktop("34")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}111{{CompatChrome(1.0)}}
Computed property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Shorthand property names{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoMobile("33")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Shorthand method names{{CompatNo}}{{CompatChrome(42.0)}}{{CompatGeckoMobile("34")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatChrome(42.0)}}
+
+ +

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/operators/operator_precedence/index.html b/files/pl/web/javascript/reference/operators/operator_precedence/index.html new file mode 100644 index 0000000000..87765f3e1a --- /dev/null +++ b/files/pl/web/javascript/reference/operators/operator_precedence/index.html @@ -0,0 +1,336 @@ +--- +title: Pierwszeństwo operatorów +slug: Web/JavaScript/Referencje/Operatory/Pierwszeństwo_operatorów +tags: + - JavaScript + - Operator + - pierwszeństwo +translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence +--- +
{{jsSidebar("Operators")}}
+ +
+ +
Pierwszeństwo operatorów ustala kolejność, w jakiej operatory są ewaluowane. Operatory z wyższym pierwszeństwem są ewaluowane jako pierwsze.
+ +
+ +

Prosty przykład:

+ +
3 + 4 * 5 // zwraca 23
+
+ +

Operator mnożenia ("*") ma wyższe pierwszeństwo niż operator dodawania ("+") i dlatego będzie ewaluowany jako pierwszy.

+ +

Łączność

+ +

Łączność określa kolejność, w jakiej przetwarzane są operatory o takim samym pierwszeństwie. Przykłądowo, rozważny wyrażenie:

+ +
a OP b OP c
+
+ +

Jeżeli  OP1 and OPmają różne poziomy pierwszeństwa operatorów (patrz tabela poniżej), operator z wyższym poziomem pierwszeństwa zostanie wykonany jako pierwszy, a kolejność zapisu nie ma znaczenia. Zwróćmy uwagę na w poniższym przykładzie, że mnożenie ma wyższy poziom pierwszeństwa i tym samym zostanie wykonane jako pierwsze, pomimo tego, że to dodawanie jest zapisane w kodzie jako pierwsze.

+ +
console.log(3 + 10 * 2);   // wynik 23
+console.log(3 + (10 * 2)); // wynik 23 ponieważ nawiasy tutaj nie mają znaczenia
+console.log((3 + 10) * 2); // wynik 26 ponieważ nawiasy zmieniają kolejność działań
+ +

Lewo-łączność (od lewej do prawej) oznacza, iż będzie ono przetworzone jako (a OP b) OP c, podczas gdy prawo-łączność (od prawej do lewej) oznacza, iż będzie ono zinterpretowane jako a OP (b OP c). Operatory przypisania są prawo-łączne, więc możesz napisać:

+ +
a = b = 5;
+
+ +

oczekując, że a i b otrzymają wartość 5. Wynika to z faktu, iż operator przypisania zwraca wartość, która jest przypisana. Najpierw wartość b ustawiana jest na 5, a następnie wartość zmiennej a jest ustawiana na wartość b.

+ +

Tabela

+ +

Poniższa tabela uporządkowana jest od najwyższego (19) do najniższego (0) pierwszeństwa.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PierwszeństwoRodzaj operatoraŁącznośćOperator
19Groupingn/a( … )
18Member Accessleft-to-right… . …
Computed Member Accessleft-to-right… [ … ]
new (z listą argumentów)n/anew … ( … )
17Wywołanie funkcjileft-to-right… ( … )
new (bez listy argumentów)right-to-leftnew …
16Postinkrementacjan/a… ++
Postdekrementacjan/a… --
15Negacja logiczna (NOT)right-to-left! …
Negacja bitowa (NOT)right-to-left~ …
Unary Plusright-to-left+ …
Unary Negationright-to-left- …
Preinkrementacjaright-to-left++ …
Predekrementacjaright-to-left-- …
typeofright-to-lefttypeof …
voidright-to-leftvoid …
deleteright-to-leftdelete …
14Mnożenieleft-to-right… * …
Dzielenieleft-to-right… / …
Reszta z dzielenialeft-to-right… % …
13Dodawanieleft-to-right… + …
Odejmowanieleft-to-right… - …
12Bitowe przesunięcie w lewoleft-to-right… << …
Bitowe przesunięcie w prawoleft-to-right… >> …
Bitowe przesunięcie w prawo bez znakuleft-to-right… >>> …
11Mniejsze niżleft-to-right… < …
Mniejsze lub równeleft-to-right… <= …
Większe niżleft-to-right… > …
Większe lub równeleft-to-right… >= …
inleft-to-right… in …
instanceofleft-to-right… instanceof …
10Równośćleft-to-right… == …
Nierównośćleft-to-right… != …
Ścisła równośćleft-to-right… === …
Ścisła nierównośćleft-to-right… !== …
9Koniunkcja bitowa (AND)left-to-right… & …
8Bitowa alternatywa wykluczająca (XOR)left-to-right… ^ …
7Alternatywa bitowa (OR)left-to-right… | …
6Koniunkcja logiczna (AND)left-to-right… && …
5Alternatywa logiczna (OR)left-to-right… || …
4Warunekright-to-left… ? … : …
3Przypisanieright-to-left… = …
… += …
… -= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2yieldright-to-leftyield …
1Spreadn/a... …
0Comma / Sequenceleft-to-right… , …
diff --git a/files/pl/web/javascript/reference/operators/pipeline_operator/index.html b/files/pl/web/javascript/reference/operators/pipeline_operator/index.html new file mode 100644 index 0000000000..9bc36390af --- /dev/null +++ b/files/pl/web/javascript/reference/operators/pipeline_operator/index.html @@ -0,0 +1,65 @@ +--- +title: Operator potoku +slug: Web/JavaScript/Referencje/Operatory/Operator_potoku +tags: + - JavaScript + - Operator + - ekxperymentalny +translation_of: Web/JavaScript/Reference/Operators/Pipeline_operator +--- +
{{jsSidebar("Operators")}} {{SeeCompatTable}}
+ +
Eskperymentalny operator potoku |> (obecnie na pierwszym etapie testów) pozwala na tworzenie łańcuchów wywołań funkcji w czytelny sposób. Dodaje lukier syntaktyczny do wywołania funkcji z pojedynczym argumentem, pozwalając przykładowo na pisanie '%21' |> decodeURI zamiast decodeURI('%21').
+ +

Składnia

+ +
wyrażenie |> funkcja
+ +

Przykłady

+ +

Łańcuchowe wywołania funkcji

+ +

Operator potoku może poprawić czytelność kodu przy łańcuchowych wywołaniach wielu funkcji.

+ +
const double = (n) => n * 2;
+const increment = (n) => n + 1;
+
+// bez operatora potoku
+double(increment(double(double(5)))); // 42
+
+// z użyciem potoku
+5 |> double |> double |> increment |> double; // 42
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + +
SpecyfikacjaStatusUwagi
Pipeline operator draftStage 1Nie jest jeszcze częścią specyfikacji ECMAScript.
+ +

Wsparcie przeglądarek

+ +
+ + +

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

+
+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/property_accessors/index.html b/files/pl/web/javascript/reference/operators/property_accessors/index.html new file mode 100644 index 0000000000..5db4669011 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/property_accessors/index.html @@ -0,0 +1,177 @@ +--- +title: Operatory pamięci +slug: Web/JavaScript/Referencje/Operatory/Operatory_pamięci +tags: + - JavaScript + - Operator +translation_of: Web/JavaScript/Reference/Operators/Property_Accessors +--- +
+
{{jsSidebar("Operators")}}
+
+ +

Operatory pamięci umożliwiają dostęp do właściwości lub metod obiektu.

+ +

Składnia

+ +
object.property
+object['property']
+
+ +

Opis

+ +

Obiekt, w rzeczywistości, jest kojarzeniową tablicą (jak mapa, słownik, hash, poglądowa tabela). Klucze w tablicy są nazwami właściwości i metod (właściwości odnoszących się do funkcji). Istnieją dwa sposoby uzyskania dostępu do właściwości: zapis z kropką lub zapis z nawiasem (operator indeksu dolnego).

+ +

Zapis z kropką

+ +
get = object.property;
+object.property = set;
+
+ +

property musi być nazwane poprawnie, według zasad JavaScript, innymi słowy: musi być sekwencją znaków alfanumerycznych (włączając w to znak podkreślenia oraz znak dolara), która nie zaczyna się od cyfry. Na przykład: object.$1 jest poprawny, natomiast object.1 jest nieprawidłowy.

+ +

Przykład:

+ +
document.createElement('pre');
+
+ +

Metoda "createElement" jest wywoływana z poziomu document.

+ +
Zapis z nawiasem
+ +
get = object[property_name];
+object[property_name] = set;
+
+ +

property_name jest łańcuchem znaków, nie musi być poprawnym identyfikatorem - może być zupełnie dowolny, przykładowo: "1foo", "!bar!" lub nawet " " (spacja).

+ +
document['createElement']('pre');
+
+ +

Mimo różnic, powyższa notacja wykonuje dokładnie to samo co zapis z kropką.

+ +

Nazwy właściwości

+ +

Nazwy właściwości muszą być łańcuchami. Oznacza to, że nazwy nie będące łańcuchami nie mogą być używane jako klucze w obiekcie. Dowolny obiekt nie będący łańcuchem, wliczając w to liczby, zostanie zrzutowany do obiektu string poprzez metodę {{jsxref("Object.toString", "toString()")}}.

+ +
var object = {};
+object['1'] = 'value';
+alert(object[1]);
+
+ +

Powyższy kod wyświetla "value", ponieważ 1 został zrzutowany do '1'.

+ +
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
+object[foo] = 'value';
+console.log(object[bar]);
+
+ +

W tym przykładzie także zostanie wypisany "value", ponieważ zarówno foo jak i bar zostały skonwertowane do tego samego łańcucha. W silniku JavaScript SpiderMonkey, łańcuch będzie wyglądał następująco: "{{ mediawiki.external('object Object') }}".

+ +

Wiązanie metod

+ +

Metoda nie jest powiązana z obiektem, którego jest metodą. Innymi słowy: this w metodzie nie jest ustawiony na sztywno. Nie musi on koniecznie odnosić się do obiektu zawierającego metodę. Zamiast tego this jest przekazywany do funkcji podczas jej wywoływania. Zajrzyj do wiązania metod po więcej informacji.

+ +

Uwaga dotycząca eval

+ +

Początkujący programiści JavaScript popełniają częsty błąd, używając eval tam gdzie może być użyty zapis z nawiasem. Poniżej zaprezentowany jest przykład.

+ +
x = eval('document.form_name.' + strFormControl + '.value');
+
+ +

eval jest wolno-działającą funkcją i powinien być jak najrzadziej używany. Zoptymalizowany fragment kodu brzmi:

+ +
x = document.form_name[strFormControl].value;
+
+ + +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-property-accessors', 'Property Accessors')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.2.1', 'Property Accessors')}}{{Spec2('ES1')}}Definicja początkowa. Zaimplementowana w JavaScript 1.0.
+ +

Kompatybilność z przeglądarkami

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Zobacz również

+ + diff --git a/files/pl/web/javascript/reference/operators/spread_syntax/index.html b/files/pl/web/javascript/reference/operators/spread_syntax/index.html new file mode 100644 index 0000000000..a45d730722 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/spread_syntax/index.html @@ -0,0 +1,244 @@ +--- +title: Składnia rozwinięcia +slug: Web/JavaScript/Referencje/Operatory/Składnia_rozwinięcia +translation_of: Web/JavaScript/Reference/Operators/Spread_syntax +--- +
{{jsSidebar("Operators")}}
+ +
Składnia rozwinięcia (ang. spread syntax) pozwala na rozwinięcie iterowalnego wyrażenia, takiego jak wyrażenie tablicowe lub ciąg znaków, tam gdzie oczekiwanych jest zero lub więcej argumentów (dla wywołań funkcji) lub elementów (dla literałów tablicowych). Pozwala również na rozwinięcie wyrażeń obiektowych w miejscach, gdzie oczekiwanych jest zero lub więcej par klucz-wartość (dla literałów obiektowych).
+ +
 
+ +
{{EmbedInteractiveExample("pages/js/expressions-spreadsyntax.html")}}
+ + + +

Składnia

+ +

Dla wywołań funkcji:

+ +
mojaFunkcja(...iterowalnyObiekt);
+
+ +

Dla literałów tablicowych lub łańcuchów znaków:

+ +
[...iterowalnyObiekt, '3', 'cztery', 5];
+ +

Dla literałów obiektowych (nowe w ECMAScript 2018):

+ +
let klonObiektu = { ...obiekt };
+ +

Przykłady

+ +

Rozwinięcie w wywołaniach funkcji

+ +

Zastąpienie apply

+ +

Powszechne jest używanie {{jsxref( "Function.prototype.apply")}} w przypadkach, w których chcemy użyć elementów tablicy jako argumentów funkcji.

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

Przy użyciu operatora rozpakowania można to zapisać jako:

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

Każdy argument na liście argumentów może użyć operatora rozpakowania, można go także używać wielokrotnie.

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

Apply for new

+ +

When calling a constructor with new, it's not possible to directly use an array and apply (apply does a [[Call]] and not a [[Construct]]). However, an array can be easily used with new thanks to spread syntax:

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

To use new with an array of parameters without spread syntax, you would have to do it indirectly through partial application:

+ +
function applyAndNew(constructor, args) {
+   function partial () {
+      return constructor.apply(this, args);
+   };
+   if (typeof constructor.prototype === "object") {
+      partial.prototype = Object.create(constructor.prototype);
+   }
+   return partial;
+}
+
+
+function myConstructor () {
+   console.log("arguments.length: " + arguments.length);
+   console.log(arguments);
+   this.prop1="val1";
+   this.prop2="val2";
+};
+
+var myArguments = ["hi", "how", "are", "you", "mr", null];
+var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
+
+console.log(new myConstructorWithArguments);
+// (internal log of myConstructor):           arguments.length: 6
+// (internal log of myConstructor):           ["hi", "how", "are", "you", "mr", null]
+// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
+ +

Rozwinięcie w literałach tablicowych

+ +

Potężniejszy literał tablicowy

+ +

Bez składni rozwinięcia, aby utworzyć nową tablicę, używając tablicy już istniejącej jako jej części, składnia literału tablicowego nie jest już wystarczająca i musimy użyć kodu imperatywnego, używając kombinacji push, splice, concat itd. Z użyciem składni rozwinięcia staje się to o wiele prostsze i bardziej zwięzłe:

+ +
var czesci = ['kotek', 'na', 'plotek'];
+var wierszyk = ['wlazl', ...czesci, 'i', 'mruga'];
+// ["wlazl", "kotek", "na", "plotek", "i", "mruga"]
+
+ +

Tak jak dla list argumentów w wywołaniach funkcji, operator ... może być użyty wielokrotnie i w każdym miejscu literału tablicowego.

+ +

Kopia tablicy

+ +
var tab = [1, 2, 3];
+var tab2 = [...tab]; // jak tab.slice()
+tab2.push(4);
+
+// tab2 staje się [1, 2, 3, 4]
+// tab pozostaje niezmieniona
+
+ +

Uwaga: Składnia rozwinięcia skutecznie sięga tylko na jeden poziom wgłąb przy kopiowaniu tablicy. W związku z tym takie podejście może być nieodpowiednie przy kopiowaniu tablic wielowymiarowych, jak pokazuje poniższy przykład (tak samo jest z {{jsxref("Object.assign()")}}  i kładnią rozwinięcia).

+ +
var a = [[1], [2], [3]];
+var b = [...a];
+b.shift().shift(); // 1
+// Tablica a została zmodyfikowana: [[], [2], [3]]
+
+ +

Lepszy sposób na łączenie tablic

+ +

{{jsxref("Array.concat")}} jest często używane do dołączania elementów jednej tablicy na koniec drugiej. Bez składni rozwinięcia wygląda to tak:

+ +
var tab1 = [0, 1, 2];
+var tab2 = [3, 4, 5];
+// Dołącz wszystkie elementy tab2 na koniec tab1
+tab1 = tab1.concat(tab2);
+ +

Przy użyciu składni rozwinięcia wygląda to natomiast tak:

+ +
var tab1 = [0, 1, 2];
+var tab2 = [3, 4, 5];
+tab1 = [...tab1, ...tab2];
+
+ +

{{jsxref("Array.unshift")}} jest często używane do dołączania elementów jednej tablicy na początek drugiej. Bez składni rozwinięcia wygląda to w następujący sposób:

+ +
var tab1 = [0, 1, 2];
+var tab2 = [3, 4, 5];
+// Dodaj wszystkie elementy tab2 na początek tab1
+Array.prototype.unshift.apply(tab1, tab2) // tab1 staje się [3, 4, 5, 0, 1, 2]
+ +

Przy użyciu składni rozwinięcia otrzymuje to następującą postać [jednak zauważ, że w tym przypadku utworzona zostaje nowa tablica tab1 – w odróżnieniu od {{jsxref("Array.unshift")}}, tab1 nie jest automatycznie modyfikowana):

+ +
var tab1 = [0, 1, 2];
+var tab2 = [3, 4, 5];
+tab1 = [...tab2, ...tab1]; // tab1 staje się [3, 4, 5, 0, 1, 2]
+
+ +

Rozwinięcie w literałach tablicowych

+ +

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

+ +

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than {{jsxref("Object.assign()")}}.

+ +
var obj1 = { foo: 'bar', x: 42 };
+var obj2 = { foo: 'baz', y: 13 };
+
+var clonedObj = { ...obj1 };
+// Object { foo: "bar", x: 42 }
+
+var mergedObj = { ...obj1, ...obj2 };
+// Object { foo: "baz", x: 42, y: 13 }
+ +

Note that {{jsxref("Object.assign()")}} triggers setters whereas spread syntax doesn't.

+ +

Note that you cannot replace nor mimic the {{jsxref("Object.assign()")}} function:

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

In the above example, the spread syntax does not work as one might expect: it spreads an array of arguments into the object literal, due to the rest parameter.

+ +

Tylko dla obiektów iterowalnych

+ +

Składnia rozwinięcia może być użyta jedynie dla obiektów iterowalnych:

+ +
var obiekt = {'klucz1': 'wartosc1'};
+var tablica = [...obiekt]; // TypeError: obiekt is not iterable
+
+ +

Rozwinięcie z wieloma wartościami

+ +

Kiedy używaż składni rozwinięcia do wywołań funkcji, musisz być świadomy możliwości przekroczenia limitu liczby argumentów w silniku JavaScript. Po więcej szczegółów zajrzyj do apply().

+ +

Składnia reszty (parametry)

+ +

Składnia reszty ang. rest syntax) wygląda dokładnie jak składnia rozwinięcia, ale jest używana do destrukturyzacji tablic i obiektów. W pewnym sensie składnia reszty jest przeciwieństwem składni rozpakowania: rozwinięcie „rozpakowuje” elementy tablicy, natomiast składnia reszty „zbiera” wiele elementów i „pakuje” je do pojedynczego elementu. Zobacz: rest parameters.

+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array-initializer')}}{{Spec2('ES2015')}}Defined in several sections of the specification: Array Initializer, Argument Lists
{{SpecName('ES2018', '#sec-object-initializer')}}{{Spec2('ES2018')}}Defined in Object Initializer
{{SpecName('ESDraft', '#sec-array-initializer')}}{{Spec2('ESDraft')}}No changes.
{{SpecName('ESDraft', '#sec-object-initializer')}}{{Spec2('ESDraft')}}No changes.
+ +

Wsparcie przeglądarek

+ + + +

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

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/super/index.html b/files/pl/web/javascript/reference/operators/super/index.html new file mode 100644 index 0000000000..c217af33e9 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/super/index.html @@ -0,0 +1,171 @@ +--- +title: super +slug: Web/JavaScript/Referencje/Operatory/super +translation_of: Web/JavaScript/Reference/Operators/super +--- +
{{jsSidebar("Operators")}}
+ +

Słowo kluczowe super jest wykorzystywane do udostępniania i korzystania z funkcji klasy po której nasz obiekt dziedziczy.

+ +

Wyrażenia super.prop i super[expr] są poprawne w każdej definicji metody zarówno w klasach i literałach obiektowych.

+ +

Składnia

+ +
super([arguments]); // wywołuje konstruktor klasy rodzica
+super.functionOnParent([arguments]);
+
+ +

Opis

+ +

W przypadku użycia w konstruktorze, słowo kluczowe super pojawia się samodzielnie i musi zostać użyte przed użyciem słowa kluczowego this . Słowo kluczowe super  można również wykorzystać do wywoływania funkcji które nasz obiekt odziedziczył po swoim rodzicu.

+ +

Przykład

+ +

Użycie super w klasach

+ +

Poniższy snippet został pobrany z próbki klasy (live demo). W tym przykładzie, super() jest wywoływane w celu uniknięcia powielania tych części konstruktora, które są wspólne zarówno dla Rectangle (trójkąta) jak i Square (kwadratu).

+ +
class Rectangle {
+  constructor(height, width) {
+    this.name = 'Rectangle';
+    this.height = height;
+    this.width = width;
+  }
+  sayName() {
+    console.log('Hi, I am a ', this.name + '.');
+  }
+  get area() {
+    return this.height * this.width;
+  }
+  set area(value) {
+    this._area = value;
+  }
+}
+
+class Square extends Rectangle {
+  constructor(length) {
+    this.height; // ReferenceError, super needs to be called first!
+
+    // Wywołanie konstruktora klasy nadrzędnej
+    // określenie szerokości i wysokości prostokąta
+    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';
+  }
+}
+ +

Super-wywołanie metod statycznych

+ +

Za pomocą super jesteś w stanie także wywołać metody statyczne.

+ +
class Rectangle {
+  constructor() {}
+  static logNbSides() {
+    return 'I have 4 sides';
+  }
+}
+
+class Square extends Rectangle {
+  constructor() {}
+  static logDescription() {
+    return super.logNbSides() + ' which are all equal';
+  }
+}
+Square.logDescription(); // 'I have 4 sides which are all equal'
+
+ +

Usuwanie właściwości z super wyrzuci błąd

+ +

Nie możesz użyć operatora usuwania oraz super.prop bądź super[expr] w celu usunięcia właściwości klasy rodzica ponieważ zostanie zwrócony błąd {{jsxref("ReferenceError")}}.

+ +
class Base {
+  constructor() {}
+  foo() {}
+}
+class Derived extends Base {
+  constructor() {}
+  delete() {
+    delete super.foo; // to jest niepoprawnie
+  }
+}
+
+new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
+ +

super.prop nie może nadpisać właściwości typu non-writable 

+ +

Definiując właściwości non-writable (niezapisywalne) np. {{jsxref("Object.defineProperty")}}, pamiętaj, że super nie może nadpisać takiej wartości.

+ +
class X {
+  constructor() {
+    Object.defineProperty(this, 'prop', {
+      configurable: true,
+      writable: false,
+      value: 1
+    });
+  }
+}
+
+class Y extends X {
+  constructor() {
+    super();
+  }
+  foo() {
+    super.prop = 2;   // Nie można nadpisać wartości
+  }
+}
+
+var y = new Y();
+y.foo(); // TypeError: "prop" is read-only
+console.log(y.prop); // 1
+
+ +

Używanie super.prop w literałach obiektowych

+ +

super może być także wykorzystane inicjalizatorze / literale obiektu.

+ +

W tym przykładzie dwa obiekty definiują swoją metodę. W drugim obiekcie, super wywołuje metodę obiektu pierwszego. To działa dzięki {{jsxref("Object.setPrototypeOf()")}} z czym jesteśmy w stanie ustawić prototyp obiektu obj2 na obj1, tak aby super było w stanie znaleźć metodę method1 w obiekcie obj1.

+ +
var obj1 = {
+  method1() {
+    console.log('method 1');
+  }
+}
+
+var obj2 = {
+  method2() {
+    super.method1();
+  }
+}
+
+Object.setPrototypeOf(obj2, obj1);
+obj2.method2(); // wypisze "method 1"
+
+ +

Specyfikacje

+ + + + + + + + + + + + +
Specyfikacja
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}
+ +

Kompatybilność

+ + + +

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

+ +

Zobacz też

+ + diff --git a/files/pl/web/javascript/reference/operators/this/index.html b/files/pl/web/javascript/reference/operators/this/index.html new file mode 100644 index 0000000000..523e210cb6 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/this/index.html @@ -0,0 +1,346 @@ +--- +title: this +slug: Web/JavaScript/Referencje/Operatory/this +translation_of: Web/JavaScript/Reference/Operators/this +--- +
+
{{jsSidebar("Operators")}}
+
+ +

Summary

+ +

W JavaScript słówko kluczowe this zachowuje się nieco inaczej w porównaniu do innych języków programowania. Istnieje również kilka różnic między trybem strict mode oraz non-strict mode.

+ +

W większości przypadków wartość this jest ustalana na podstawie tego, jak wywołana została dana funkcja. Wartość ta nie może być przypisana podczas wykonywania się funkcji i może być inna za każdym wywołaniem. ES5 wprowadziło metodę bind dzięki której możemy przypisać wartość this w funkcji, niezależnie od tego jak została ona wywołana.

+ +

Syntax

+ +
this
+ +

Global context

+ +

In the global execution context (outside of any function), this refers to the global object, whether in strict mode or not.

+ +
console.log(this.document === document); // true
+
+// In web browsers, the window object is also the global object:
+console.log(this === window); // true
+
+this.a = 37;
+console.log(window.a); // 37
+
+ +

Function context

+ +

Inside a function, the value of this depends on how the function is called.

+ +

Simple call

+ +
function f1(){
+  return this;
+}
+
+f1() === window; // global object
+
+ +

In this case, the value of this is not set by the call. Since the code is not in strict mode, the value of this must always be an object so it defaults to the global object.

+ +
function f2(){
+  "use strict"; // see strict mode
+  return this;
+}
+
+f2() === undefined;
+
+ +

In strict mode, the value of this remains at whatever it's set to when entering the execution context. If it's not defined, it remains undefined. It can also be set to any value, such as null or 42 or "I am not this".

+ +
Note: In the second example, this should be undefined, because f2 was called without providing any base (e.g. window.f2()). This feature wasn't implemented in some browsers when they first started to support strict mode. As a result, they incorrectly returned the window object.
+ +

As an object method

+ +

When a function is called as a method of an object, its this is set to the object the method is called on.

+ +

In the following example, when o.f() is invoked, inside the function this is bound to the o object.

+ +
var o = {
+  prop: 37,
+  f: function() {
+    return this.prop;
+  }
+};
+
+console.log(o.f()); // logs 37
+
+ +

Note that this behavior is not at all affected by how or where the function was defined. In the previous example, we defined the function inline as the f member during the definition of o. However, we could have just as easily defined the function first and later attached it to o.f. Doing so results in the same behavior:

+ +
var o = {prop: 37};
+
+function independent() {
+  return this.prop;
+}
+
+o.f = independent;
+
+console.log(o.f()); // logs 37
+
+ +

This demonstrates that it matters only that the function was invoked from the f member of o.

+ +

Similarly, the this binding is only affected by the most immediate member reference. In the following example, when we invoke the function, we call it as a method g of the object o.b. This time during execution, this inside the function will refer to o.b. The fact that the object is itself a member of o has no consequence; the most immediate reference is all that matters.

+ +
o.b = {g: independent, prop: 42};
+console.log(o.b.g()); // logs 42
+
+ +

this on the object's prototype chain

+ +

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method was on the object.

+ +
var o = {f:function(){ return this.a + this.b; }};
+var p = Object.create(o);
+p.a = 1;
+p.b = 4;
+
+console.log(p.f()); // 5
+
+ +

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

+ +

this with a getter or setter

+ +

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

+ +
function modulus(){
+  return Math.sqrt(this.re * this.re + this.im * this.im);
+}
+
+var o = {
+  re: 1,
+  im: -1,
+  get phase(){
+    return Math.atan2(this.im, this.re);
+  }
+};
+
+Object.defineProperty(o, 'modulus', {
+    get: modulus, enumerable:true, configurable:true});
+
+console.log(o.phase, o.modulus); // logs -0.78 1.4142
+
+ +

As a constructor

+ +

When a function is used as a constructor (with the new keyword), its this is bound to new object being constructed.

+ +

Note: while the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

+ +
/*
+ * Constructors work like this:
+ *
+ * function MyConstructor(){
+ *   // Actual function body code goes here.
+ *   // Create properties on |this| as
+ *   // desired by assigning to them.  E.g.,
+ *   this.fum = "nom";
+ *   // et cetera...
+ *
+ *   // If the function has a return statement that
+ *   // returns an object, that object will be the
+ *   // result of the |new| expression.  Otherwise,
+ *   // the result of the expression is the object
+ *   // currently bound to |this|
+ *   // (i.e., the common case most usually seen).
+ * }
+ */
+
+function C(){
+  this.a = 37;
+}
+
+var o = new C();
+console.log(o.a); // logs 37
+
+
+function C2(){
+  this.a = 37;
+  return {a:38};
+}
+
+o = new C2();
+console.log(o.a); // logs 38
+
+ +

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead, because it gets executed, but it can be eliminated with no outside effects.)

+ +

call and apply

+ +

Where a function uses the this keyword in its body, its value can be bound to a particular object in the call using the call or apply methods that all functions inherit from Function.prototype.

+ +
function add(c, d){
+  return this.a + this.b + c + d;
+}
+
+var o = {a:1, b:3};
+
+// The first parameter is the object to use as
+// 'this', subsequent parameters are passed as
+// arguments in the function call
+add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16
+
+// The first parameter is the object to use as
+// 'this', the second is an array whose
+// members are used as the arguments in the function call
+add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34
+
+ +

Note that with call and apply, if the value passed as this is not an object, an attempt will be made to convert it to an object using the internal ToObject operation. So if the value passed is a primitive like 7 or 'foo', it will be converted to an Object using the related constructor, so the primitive number 7 is converted to an object as if by new Number(7) and the string 'foo' to an object as if by new String('foo'), e.g.

+ +
function bar() {
+  console.log(Object.prototype.toString.call(this));
+}
+
+bar.call(7); // [object Number]
+
+ +

The bind method

+ +

ECMAScript 5 introduced Function.prototype.bind. Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, regardless of how the function is being used.

+ +
function f(){
+  return this.a;
+}
+
+var g = f.bind({a:"azerty"});
+console.log(g()); // azerty
+
+var o = {a:37, f:f, g:g};
+console.log(o.f(), o.g()); // 37, azerty
+
+ +

As a DOM event handler

+ +

When a function is used as an event handler, its this is set to the element the event fired from (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener).

+ +
// When called as a listener, turns the related element blue
+function bluify(e){
+  // Always true
+  console.log(this === e.currentTarget);
+  // true when currentTarget and target are the same object
+  console.log(this === e.target);
+  this.style.backgroundColor = '#A5D9F3';
+}
+
+// Get a list of every element in the document
+var elements = document.getElementsByTagName('*');
+
+// Add bluify as a click listener so when the
+// element is clicked on, it turns blue
+for(var i=0 ; i<elements.length ; i++){
+  elements[i].addEventListener('click', bluify, false);
+}
+ +

In an in–line event handler

+ +

When code is called from an in–line handler, its this is set to the DOM element on which the listener is placed:

+ +
<button onclick="alert(this.tagName.toLowerCase());">
+  Show this
+</button>
+
+ +

The above alert shows button. Note however that only the outer code has its this set this way:

+ +
<button onclick="alert((function(){return this}()));">
+  Show inner this
+</button>
+
+ +

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
ECMAScript 1st Edition.StandardInitial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-11.1.1', 'The this keyword')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-this-keyword', 'The this keyword')}}{{Spec2('ES6')}}
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

See also

+ + diff --git a/files/pl/web/javascript/reference/operators/typeof/index.html b/files/pl/web/javascript/reference/operators/typeof/index.html new file mode 100644 index 0000000000..dfb169a9b5 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/typeof/index.html @@ -0,0 +1,91 @@ +--- +title: Operator typeof +slug: Web/JavaScript/Referencje/Operatory/Operator_typeof +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/typeof +--- +

 

+ +

Podsumowanie

+ +

Operator typeof używa się na jeden z poniższych sposobów:

+ +
    +
  1. typeof operand
  2. +
  3. typeof (operand )
  4. +
+ +

Operator typeof zwraca łańcuch zawierający type of unevaluated operand: jak przetłumaczyć unevaluated?typ operandu. operand jest łańcuchem znaków, zmienną, słowem kluczowym lub obiektem, którego typ ma zostać zwrócony. Zastosowanie nawiasów jest opcjonalne.

+ + + + + + + + + + + + + + + +
Operator
Zaimplementowany w:JavaScript 1.1
Wersja ECMA:ECMA-262
+ +

Zakładamy, że możemy zdefiniować następujące zmienne:

+ +
var myFun = new Function("5+2")
+var shape="round"
+var size=1
+var today=new Date()
+
+ +

Operator typeof zwróci następujący rezultat dla tych zmiennych:

+ +
typeof myFun is object
+typeof shape is string
+typeof size is number
+typeof today is object
+typeof dontExist is undefined
+
+ +

Dla słów kluczowych true oraz null, operator typeof zwraca następujący rezultat:

+ +
typeof true is boolean
+typeof null is object
+
+ +

Dla liczby lub łańcucha znaków, operator typeof zwraca następujący rezultat:

+ +
typeof 62 is number
+typeof 'Hello world' is string
+
+ +

Dla własności wartości, operator typeof zwraca typ wartości własności, jakie składają się na treść:

+ +
typeof document.lastModified is string
+typeof window.length is number
+typeof Math.LN2 is number
+
+ +

Dla metod i funkcji, operator typeof zwraca następujący rezultat:

+ +
typeof blur is function
+typeof eval is function
+typeof parseInt is function
+typeof shape.split is function
+
+ +

Dla obiektów predefiniowanych, operator typeof zwraca następujący rezultat:

+ +
typeof Date is function
+typeof Function is function
+typeof Math is function
+typeof Option is function
+typeof String is function
+
diff --git a/files/pl/web/javascript/reference/operators/void/index.html b/files/pl/web/javascript/reference/operators/void/index.html new file mode 100644 index 0000000000..65b3fe8fa2 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/void/index.html @@ -0,0 +1,51 @@ +--- +title: Operator void +slug: Web/JavaScript/Referencje/Operatory/Operator_void +tags: + - Dokumentacja_JavaScript + - Dokumentacje + - JavaScript + - Wszystkie_kategorie +translation_of: Web/JavaScript/Reference/Operators/void +--- +

 

+ +

Podsumowanie

+ +

Operator void może być używany na jeden z dwóch sposobów:

+ +
    +
  1. void (wyrażenie )
  2. +
  3. void wyrażenie
  4. +
+ +

Operator void określa wyrażenie, które ma zostać ocenione bez zwracania wartości. wyrażenie jest wyrażeniem JavaScript, które ma zostać ocenione. Nawiasy dookoła wyrażenia są opcjonalne, ale używanie ich jest w dobrym stylu.

+ + + + + + + + + + + + + + + +
Operator
Zaimplementowany w:JavaScript 1.1
Wersja ECMA:ECMA-262
+ +

Możesz użyć operatora void, aby określić wyrażenie jako hipertekstowy odnośnik. Wyrażenie jest oceniane, ale nie jest ładowane w miejsce aktualnego dokumentu.

+ +

Poniższy kod tworzy hipertekstowy odnośnik, który nie wykonuje nic po kliknięciu go przez użytkownika. Gdy użytkownik kliknie odnośnik, void(0) zostanie oceniony jako 0, jednak nie ma to żadnego efektu w JavaScripcie.

+ +
<a href="javascript:void(0)">Kliknij tutaj, żeby nic się nie stało</a>
+
+ +

Poniższy kod tworzy hipertekstowy odnośnik, który wysyła formularz, gdy zostanie kliknięty przez użytkownika.

+ +
<a href="javascript:void(document.form.submit())">
+Kliknij tutaj, aby wysłać.</a>
+
diff --git a/files/pl/web/javascript/reference/operators/yield/index.html b/files/pl/web/javascript/reference/operators/yield/index.html new file mode 100644 index 0000000000..8d814a5aa8 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/yield/index.html @@ -0,0 +1,168 @@ +--- +title: yield +slug: Web/JavaScript/Referencje/Operatory/yield +translation_of: Web/JavaScript/Reference/Operators/yield +--- +
{{jsSidebar("Operators")}}
+ +

Słowo kluczowe yield jest używane do zatrzymania i powrotu funkcji generatora ({{jsxref("Statements/function*", "function*")}} lub legacy generator function).

+ +

Syntax

+ +
[rv] = yield [expression];
+ +
+
expression
+
Definiuje wartość która ma być zwrócona przez funkcję generatora przez the iterator protocol, jeżeli pominięte, zostanie zwrócone undefined.
+
rv
+
+

Zwraca opcjonalną wartość przekazaną do metody next() generatora, do powrotu do jej wykonania.

+
+
+ +

Description

+ +

The yield keyword causes generator function execution to pause and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.

+ +

The yield keyword actually returns an IteratorResult object with two properties, value and done. The value property is the result of evaluating the yield expression, and done is false, indicating that the generator function has not fully completed.

+ +

Once paused on a yield expression, the generator's code execution remains paused until the generator's next() method is called. Each time the generator's next() method is called, the generator resumes execution and runs until it reaches one of the following:

+ + + +

If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation.

+ +

Between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to {{jsxref("Generator.prototype.next()")}}, generators offer enormous power and control.

+ +

Examples

+ +

The following code is the declaration of an example generator function.

+ +
function* foo() {
+  var index = 0;
+  while (index <= 2)
+    yield index++;
+}
+ +

Once a generator function is defined, it can be used by constructing an iterator as shown.

+ +
var iterator = foo();
+console.log(iterator.next()); // { value: 0, done: false }
+console.log(iterator.next()); // { value: 1, done: false }
+console.log(iterator.next()); // { value: 2, done: false }
+console.log(iterator.next()); // { value: undefined, done: true }
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari("10")}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoDesktop("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari("10")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}{{ CompatUnknown}}{{CompatSafari("10")}}
IteratorResult object instead of throwing{{CompatUnknown}}{{CompatGeckoMobile("29.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari("10")}}
+
+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/pl/web/javascript/reference/operators/yield_star_/index.html b/files/pl/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..ddef530622 --- /dev/null +++ b/files/pl/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,200 @@ +--- +title: yield* +slug: Web/JavaScript/Referencje/Operatory/yield* +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +
{{jsSidebar("Operators")}}
+ +

Wyrażenie yield*  służy do wydelegowania działania generatora do innego {{jsxref("Statements/function*", "generatora")}} lub obiektu iterowalnego.

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

Składnia

+ +
 yield* [[expression]];
+ +
+
expression
+
Wyrażenie, które zwraca iterowalny obiekt lub generator.
+
+ +

Opis

+ +

yield* iteruje po iterowalnym obiekcie i wywołuje yield z każdą kolejną zwracaną przez niego wartością.

+ +

Wartość samego yield* jest wartością zwróconą przez iterator w momencie jego zakończenia (tzn. kiedy done ma wartość true).

+ +

Przykłady

+ +

Delegowanie logiki do osobnego generatora

+ +

W poniższym kodzie wartości yeld dla  g1() zwracane są przy wywołaniu next() dokładnie tak samo jak te, które zwraca yeld generatora g2().

+ +
function* g1() {
+  yield 2;
+  yield 3;
+  yield 4;
+}
+
+function* g2() {
+  yield 1;
+  yield* g1();
+  yield 5;
+}
+
+var iterator = g2();
+
+console.log(iterator.next()); // {value: 1, done: false}
+console.log(iterator.next()); // {value: 2, done: false}
+console.log(iterator.next()); // {value: 3, done: false}
+console.log(iterator.next()); // {value: 4, done: false}
+console.log(iterator.next()); // {value: 5, done: false}
+console.log(iterator.next()); // {value: undefined, done: true}
+
+ +

Inne obiekty iterowalne

+ +

yield* może wywoływać yield z wartościami dostarczanymi przez inne rodzje obiektów iterowalnych , np. tablice, stringi lub obiekt arguments.

+ +
function* g3() {
+  yield* [1, 2];
+  yield* '34';
+  yield* Array.from(arguments);
+}
+
+var iterator = g3(5, 6);
+
+console.log(iterator.next()); // {value: 1, done: false}
+console.log(iterator.next()); // {value: 2, done: false}
+console.log(iterator.next()); // {value: "3", done: false}
+console.log(iterator.next()); // {value: "4", done: false}
+console.log(iterator.next()); // {value: 5, done: false}
+console.log(iterator.next()); // {value: 6, done: false}
+console.log(iterator.next()); // {value: undefined, done: true}
+
+ +

Wartość samego wyrażenia yield*

+ +

yield* jest wyrażeniem (expression) a nie statement, więc rozwiązuje się do konkretnej wartości.

+ +
function* g4() {
+  yield* [1, 2, 3];
+  return 'foo';
+}
+
+var result;
+
+function* g5() {
+  result = yield* g4();
+}
+
+var iterator = g5();
+
+console.log(iterator.next()); // {value: 1, done: false}
+console.log(iterator.next()); // {value: 2, done: false}
+console.log(iterator.next()); // {value: 3, done: false}
+console.log(iterator.next()); // {value: undefined, done: true},
+                              // g4() zwrócił w tym momencie {value: 'foo', done: true}
+
+console.log(result);          // "foo"
+
+ +

Specyfikacje

+ + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#', 'Yield')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#', 'Yield')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("27.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari("10")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile("27.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari("10")}}
+
+ +

Firefox-specific notes

+ + + +

See also

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