aboutsummaryrefslogtreecommitdiff
path: root/files/pl/web/javascript/reference/classes/constructor/index.html
blob: 8d11cce8f092ffa46d4aee0bf0ac510f2b2047e0 (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
---
title: Konstruktor
slug: Web/JavaScript/Reference/Classes/constructor
tags:
  - Classes
  - JavaScript
  - Language feature
translation_of: Web/JavaScript/Reference/Classes/constructor
original_slug: Web/JavaScript/Reference/Classes/Konstruktor
---
<div>{{jsSidebar("Classes")}}</div>

<p>Konstruktor <span id="result_box" lang="pl"><span>jest specjalną metodą tworzenia i inicjowania obiektu utworzonego w klasie.</span></span></p>

<p>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</p>

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

<pre class="syntaxbox notranslate">constructor([arguments]) { ... }</pre>

<h2 id="Opis">Opis</h2>

<p>Konstruktor umożliwia zdefiniowanie inicjalizacji obiektu, która musi się wykonać, zanim będzie można wywołać metody obiektu.</p>

<pre class="brush: js notranslate">class Person {

  constructor(name) {
    this.name = name;
  }

  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }

}

const otto = new Person('Otto');

otto.introduce();</pre>

<p>Jeśli niestandardowy konstruktor nie został podany, to domyślny konstruktor będzie użyty. Dla klas bazowych konstruktor domyślny jest pusty:</p>

<pre class="brush: js notranslate">constructor() {}</pre>

<p>Dla klas pochodnych domyślny konstruktor wywołuje konstruktor klasy nadrzędnej:</p>

<pre class="brush: js notranslate">constructor(...args) {
  super(...args);
}</pre>

<p>Pozwala to na działanie takiego kodu:</p>

<pre class="brush: js notranslate">class ValidationError extends Error {

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }

}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
   if (error instanceof ValidationError) {
    console.log(error.name); // This is Error instead of ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}</pre>

<p>Klasa <code>ValidationError</code> nie musi mieć niestandardowego konstruktora, ponieważ domyślny konstruktor wywołuje konstruktor klasy <code>Error</code>.</p>

<p>Jeśli jednak klasa <code>ValidationError</code> ma niestandardowy konstruktor, to musi on wywoływać konstruktor klasy nadrzędnej przy użyciu <code>super</code>:</p>

<pre class="brush: js notranslate">class ValidationError extends Error {

  constructor(message) {
    super(message);  // call parent class constructor
    this.name = 'ValidationError';
    this.code = '42';
  }

  printCustomerMessage() {
     return `Validation failed :-( (details: ${this.message}, code: ${this.code})`;
  }

}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
   if (error instanceof ValidationError) {
    console.log(error.name); // Now this is ValidationError!
    console.log(error.printCustomerMessage());
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}</pre>

<p>Wewnątrz klasy może być tylko jedna metoda nazwana <code>constructor</code>. Jeżeli <code>constructor</code> wystąpi więcej niż jeden raz, to wygeneruje błąd {{jsxref("SyntaxError")}}.</p>

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

<h3 id="Używanie_konstruktora">Używanie konstruktora</h3>

<p>Fragment kodu pochodzi z <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>).</p>

<pre class="brush: js notranslate">class Square extends Polygon {
  constructor(length) {
    // Wywołanie konstruktora klasy nadrzędnej
    // określenie szerokości i wysokości wielokątu
    super(length, length);
    // Uwaga: W pochodnych klasach, super() musi być wywołane wcześniej niż
    // pierwsze użycie 'this'. W przeciwnym wypadku pojawi się błąd odniesienia.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}</pre>

<h3 id="Inny_przykład">Inny przykład</h3>

<p>W tym przykładzie klasa <code>Square</code> jest zmieniona — ale konstruktor klasy <code>Polygon</code> nadal jest wywoływany przy tworzeniu nowej instancji klasy <code>Square</code>.</p>

<pre class="brush: js notranslate">class Polygon {
    constructor() {
        this.name = "Polygon";
    }
}

class Square extends Polygon {
    constructor() {
        super();
    }
}

class Rectangle {}

Object.setPrototypeOf(Square.prototype, Rectangle.prototype);

console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true

let newInstance = new Square();
console.log(newInstance.name); //Polygon</pre>

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

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specyfikacja</th>
   <th scope="col">Status</th>
   <th scope="col">Komentarz</th>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Kompatybilność">Kompatybilność</h2>

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

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

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li>
</ul>