aboutsummaryrefslogtreecommitdiff
path: root/files/pl/web/javascript/reference/classes/public_class_fields/index.html
blob: 780300e64f3c12cae103b8f02155f495b60fbb32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
---
title: Public class fields
slug: Web/JavaScript/Reference/Classes/Public_class_fields
tags:
  - Classes
  - JavaScript
  - Language feature
translation_of: Web/JavaScript/Reference/Classes/Public_class_fields
---
<div>{{JsSidebar("Classes")}}</div>

<div>
<div class="note">
<p><strong>Ta strona opisuje funkcjonalności eksperymentalne</strong></p>

<p>Deklaracje pól publicznych i prywatnych są <a class="external external-icon" href="https://github.com/tc39/proposal-class-fields" rel="noopener">funkcjonalnościami eksperymentalnymi (stage 3)</a> zaproponowanymi na <a class="external external-icon" href="https://tc39.github.io/beta/" rel="noopener">TC39</a>.</p>

<p>Wsparcie przeglądarek jest ograniczone, ale ta funkcjonalność może być używana przy użyciu systemów takich jak <a class="external external-icon" href="https://babeljs.io/" rel="noopener">Babel</a>. Zobacz <a href="#Kompatybilność">tabelę kompatybilności</a> poniżej.</p>
</div>
</div>

<p>Zarówno statyczne, jak i instancyjne pola publiczne są właściwościami zapisywalnymi, wyliczalnymi i konfigurowalnymi. W przeciwieństwie do ich prywatnych odpowiedników uczestniczą w dziedziczeniu prototypów.</p>

<h2 id="Składnia">Składnia</h2>

<pre class="syntaxbox notranslate">class ClassWithInstanceField {
  instanceField = 'instance field'
}

class ClassWithStaticField {
  static staticField = 'static field'
}

class ClassWithPublicInstanceMethod {
  publicMethod() {
    return 'hello world'
  }
}
</pre>

<h2 id="Przykłady">Przykłady</h2>

<h3 id="Publiczne_pola_statyczne">Publiczne pola statyczne</h3>

<p>Publiczne pola statyczne są użyteczne, gdy chcesz, aby pole istniało tylko raz dla danej klasy, a nie dla każdej tworzonej instancji klasy. Jest to użyteczne w przypadku cache'ów, stałej konfiguracji lub innych danych, które nie muszą być replikowane na wszystkich instancjach.</p>

<p>Publiczne pola statyczne są deklarowane z użyciem słowa kluczowego <code>static</code>. Są dodawane do konstruktora klasy podczas jej wykonywania z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}}. Są one dostępne z poziomu konstruktora klasy.</p>

<pre class="brush: js notranslate">class ClassWithStaticField {
  static staticField = 'static field'
}

console.log(ClassWithStaticField.staticField)
// expected output: "static field"​
</pre>

<p>Pola bez inicjalizatorów są ustawiane na <code>undefined</code>.</p>

<pre class="brush: js notranslate">class ClassWithStaticField {
  static staticField
}

console.assert(ClassWithStaticField.hasOwnProperty('staticField'))
console.log(ClassWithStaticField.staticField)
// expected output: "undefined"</pre>

<p>Publiczne pola statyczne nie są inicjalizowane ponownie w podklasach, ale można uzyskać do nich dostęp przez łańcuch prototypów.</p>

<pre class="brush: js notranslate">class ClassWithStaticField {
  static baseStaticField = 'base field'
}

class SubClassWithStaticField extends ClassWithStaticField {
  static subStaticField = 'sub class field'
}

console.log(SubClassWithStaticField.subStaticField)
// expected output: "sub class field"

console.log(SubClassWithStaticField.baseStaticField)
// expected output: "base field"</pre>

<p>Przy inicjalizacji pól, <code>this</code> odnosi się do konstruktora klasy. Można się również odwołać przez nazwę i użyć <code>super</code> do otrzymania konstruktora klasy nadrzędnej (jeżeli istnieje).</p>

<pre class="brush: js notranslate">class ClassWithStaticField {
  static baseStaticField = 'base static field'
  static anotherBaseStaticField = this.baseStaticField

  static baseStaticMethod() { return 'base static method output' }
}

class SubClassWithStaticField extends ClassWithStaticField {
  static subStaticField = super.baseStaticMethod()
}

console.log(ClassWithStaticField.anotherBaseStaticField)
// expected output: "base static field"

console.log(SubClassWithStaticField.subStaticField)
// expected output: "base static method output"
</pre>

<h3 id="Publiczne_pola_instancyjne">Publiczne pola instancyjne</h3>

<p>Publiczne pola instancyjne istnieją na każdej utworzonej instancji danej klasy. Poprzez zadeklarowanie pola publicznego, można zapewnić, że pole jest zawsze obecne, a definicja klasy jest bardziej samodokumentująca.</p>

<p>Publiczne pola instancyjne są dodawane przy użyciu {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonywania konstruktora klasy, lub po wywołaniu metody <code>super()</code>.</p>

<pre class="brush: js notranslate">class ClassWithInstanceField {
  instanceField = 'instance field'
}

const instance = new ClassWithInstanceField()
console.log(instance.instanceField)
// expected output: "instance field"</pre>

<p>Pola bez inicjalizatorów są ustawiane na <code>undefined</code>.</p>

<pre class="brush: js notranslate">class ClassWithInstanceField {
  instanceField
}

const instance = new ClassWithInstanceField()
console.assert(instance.hasOwnProperty('instanceField'))
console.log(instance.instanceField)
// expected output: "undefined"</pre>

<p>Podobnie jak właściwości, nazwy pól mogą być obliczane.</p>

<pre class="brush: js notranslate">const PREFIX = 'prefix'

class ClassWithComputedFieldName {
    [`${PREFIX}Field`] = 'prefixed field'
}

const instance = new ClassWithComputedFieldName()
console.log(instance.prefixField)
// expected output: "prefixed field"</pre>

<p>Przy inicjalizacji pól <code>this</code> odnosi się do instancji klasy. Tak jak w publicznych metodach instancji, można odnieść się do klasy nadrzędnej, używając <code>super</code>.</p>

<pre class="brush: js notranslate">class ClassWithInstanceField {
  baseInstanceField = 'base field'
  anotherBaseInstanceField = this.baseInstanceField
  baseInstanceMethod() { return 'base method output' }
}

class SubClassWithInstanceField extends ClassWithInstanceField {
  subInstanceField = super.baseInstanceMethod()
}

const base = new ClassWithInstanceField()
const sub = new SubClassWithInstanceField()

console.log(base.anotherBaseInstanceField)
// expected output: "base field"

console.log(sub.subInstanceField)
// expected output: "base method output"</pre>

<h3 id="Publiczne_metody">Publiczne metody</h3>

<h4 id="Publiczne_metody_statyczne">Publiczne metody statyczne</h4>

<p>Słowo kluczowe <code><strong>static</strong></code> definiuje metodę statyczną dla klasy. Metody statyczne nie są wywoływane na instancjach klasy, ale na samej klasie. Są to często funkcje użytkowe, takie jak funkcje tworzenia lub klonowania obiektów.</p>

<pre class="brush: js notranslate">class ClassWithStaticMethod {
  static staticMethod() {
    return 'static method has been called.';
  }
}

console.log(ClassWithStaticMethod.staticMethod());
// expected output: "static method has been called."</pre>

<p>Metody statyczne są dodawane do konstruktora klasy z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonania klasy. Te metody są zapisywalne, niewyliczalne i konfigurowalne.</p>

<h4 id="Publiczne_metody_instancyjne">Publiczne metody instancyjne</h4>

<p>Jak nazwa wskazuje, publiczne metody instancji to metody dostępne na instancjach klasy.</p>

<pre class="brush: js notranslate">class ClassWithPublicInstanceMethod {
  publicMethod() {
    return 'hello world'
  }
}

const instance = new ClassWithPublicInstanceMethod()
console.log(instance.publicMethod())
// expected output: "hello worl​d"</pre>

<p>Publiczne metody instancji są dodawane do prototypu klasy z użyciem {{jsxref("Global_Objects/Object/defineProperty", "Object.defineProperty()")}} podczas wykonania klasy. Te metody są zapisywalne, niewyliczalne i konfigurowalne.</p>

<p>Publiczne metody mogą używać async lub być generatorami.</p>

<pre class="brush: js notranslate">class ClassWithFancyMethods {
  *generatorMethod() { }
  async asyncMethod() { }
  async *asyncGeneratorMethod() { }
}</pre>

<p>Wewnątrz metod instancji, <code>this</code> odnosi się do samej instancji. W podklasach można użyć <code>super</code> do dostępu do prototypu klasy nadrzędnej, umożliwiając wywoływanie metod tej klasy.</p>

<pre class="brush: js notranslate">class BaseClass {
  msg = 'hello world'
  basePublicMethod() {
    return this.msg
  }
}

class SubClass extends BaseClass {
  subPublicMethod() {
    return super.basePublicMethod()
  }
}

const instance = new SubClass()
console.log(instance.subPublicMethod())
// expected output: "hello worl​d"
</pre>

<p>Getter'y i setter'y to specjalne metody, które wiążą się z właściwością danej klasy i są wywoływane, gdy właściwość jest odczytywana lub modyfikowana. Do tworzenia getter'ów i setter'ów należy użyć <a href="https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Functions/get">get</a> and <a href="https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Functions/set">set</a>.</p>

<pre class="brush: js notranslate">class ClassWithGetSet {
  #msg = 'hello world'
  get msg() {
    return this.#msg
  }
  set msg(x) {
    this.#msg = `hello ${x}`
  }
}

const instance = new ClassWithGetSet()
console.log(instance.msg)
// expected output: "hello worl​d"

instance.msg = 'cake'
console.log(instance.msg)
// expected output: "hello cake"
</pre>

<h2 id="Specyfikacje">Specyfikacje</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specyfikacja</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('Public and private instance fields', '#prod-FieldDefinition', 'FieldDefinition')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Kompatybilność_2"><a name="Kompatybilność">Kompatybilność</a></h2>



<p>{{Compat("javascript.classes.public_class_fields")}}</p>

<h2 id="Zobacz_też">Zobacz też</h2>

<ul>
 <li><a href="/pl/docs/Web/JavaScript/Reference/Classes/Private_class_fields">Private class fields</a></li>
 <li><a href="https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html">The Semantics of All JS Class Elements</a></li>
</ul>