diff options
Diffstat (limited to 'files/pl/web/javascript/reference/classes/constructor')
-rw-r--r-- | files/pl/web/javascript/reference/classes/constructor/index.html | 188 |
1 files changed, 188 insertions, 0 deletions
diff --git a/files/pl/web/javascript/reference/classes/constructor/index.html b/files/pl/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..353adecd19 --- /dev/null +++ b/files/pl/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,188 @@ +--- +title: Konstruktor +slug: Web/JavaScript/Reference/Classes/Konstruktor +tags: + - Classes + - JavaScript + - Language feature +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +<div>{{jsSidebar("Classes")}}</div> + +<p>Konstruktor <span id="result_box" lang="pl"><span>jest specjalną metodą tworzenia i inicjowania obiektu utworzonego w klasie.</span></span></p> + +<p>{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}</p> + +<h2 id="Składnia">Składnia</h2> + +<pre class="syntaxbox notranslate">constructor([arguments]) { ... }</pre> + +<h2 id="Opis">Opis</h2> + +<p>Konstruktor umożliwia zdefiniowanie inicjalizacji obiektu, która musi się wykonać, zanim będzie można wywołać metody obiektu.</p> + +<pre class="brush: js notranslate">class Person { + + constructor(name) { + this.name = name; + } + + introduce() { + console.log(`Hello, my name is ${this.name}`); + } + +} + +const otto = new Person('Otto'); + +otto.introduce();</pre> + +<p>Jeśli niestandardowy konstruktor nie został podany, to domyślny konstruktor będzie użyty. Dla klas bazowych konstruktor domyślny jest pusty:</p> + +<pre class="brush: js notranslate">constructor() {}</pre> + +<p>Dla klas pochodnych domyślny konstruktor wywołuje konstruktor klasy nadrzędnej:</p> + +<pre class="brush: js notranslate">constructor(...args) { + super(...args); +}</pre> + +<p>Pozwala to na działanie takiego kodu:</p> + +<pre class="brush: js notranslate">class ValidationError extends Error { + + printCustomerMessage() { + return `Validation failed :-( (details: ${this.message})`; + } + +} + +try { + throw new ValidationError("Not a valid phone number"); +} catch (error) { + if (error instanceof ValidationError) { + console.log(error.name); // This is Error instead of ValidationError! + console.log(error.printCustomerMessage()); + } else { + console.log('Unknown error', error); + throw error; + } +}</pre> + +<p>Klasa <code>ValidationError</code> nie musi mieć niestandardowego konstruktora, ponieważ domyślny konstruktor wywołuje konstruktor klasy <code>Error</code>.</p> + +<p>Jeśli jednak klasa <code>ValidationError</code> ma niestandardowy konstruktor, to musi on wywoływać konstruktor klasy nadrzędnej przy użyciu <code>super</code>:</p> + +<pre class="brush: js notranslate">class ValidationError extends Error { + + constructor(message) { + super(message); // call parent class constructor + this.name = 'ValidationError'; + this.code = '42'; + } + + printCustomerMessage() { + return `Validation failed :-( (details: ${this.message}, code: ${this.code})`; + } + +} + +try { + throw new ValidationError("Not a valid phone number"); +} catch (error) { + if (error instanceof ValidationError) { + console.log(error.name); // Now this is ValidationError! + console.log(error.printCustomerMessage()); + } else { + console.log('Unknown error', error); + throw error; + } +}</pre> + +<p>Wewnątrz klasy może być tylko jedna metoda nazwana <code>constructor</code>. Jeżeli <code>constructor</code> wystąpi więcej niż jeden raz, to wygeneruje błąd {{jsxref("SyntaxError")}}.</p> + +<h2 id="Przykłady">Przykłady</h2> + +<h3 id="Używanie_konstruktora">Używanie konstruktora</h3> + +<p>Fragment kodu pochodzi z <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a> (<a href="https://googlechrome.github.io/samples/classes-es6/index.html">live demo</a>).</p> + +<pre class="brush: js notranslate">class Square extends Polygon { + constructor(length) { + // Wywołanie konstruktora klasy nadrzędnej + // określenie szerokości i wysokości wielokątu + super(length, length); + // Uwaga: W pochodnych klasach, super() musi być wywołane wcześniej niż + // pierwsze użycie 'this'. W przeciwnym wypadku pojawi się błąd odniesienia. + this.name = 'Square'; + } + + get area() { + return this.height * this.width; + } + + set area(value) { + this.area = value; + } +}</pre> + +<h3 id="Inny_przykład">Inny przykład</h3> + +<p>W tym przykładzie klasa <code>Square</code> jest zmieniona — ale konstruktor klasy <code>Polygon</code> nadal jest wywoływany przy tworzeniu nowej instancji klasy <code>Square</code>.</p> + +<pre class="brush: js notranslate">class Polygon { + constructor() { + this.name = "Polygon"; + } +} + +class Square extends Polygon { + constructor() { + super(); + } +} + +class Rectangle {} + +Object.setPrototypeOf(Square.prototype, Rectangle.prototype); + +console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false +console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true + +let newInstance = new Square(); +console.log(newInstance.name); //Polygon</pre> + +<h2 id="Specyfikacje">Specyfikacje</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specyfikacja</th> + <th scope="col">Status</th> + <th scope="col">Komentarz</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Kompatybilność">Kompatybilność</h2> + +<p>{{Compat("javascript.classes.constructor")}}</p> + +<h2 id="Zobacz_też">Zobacz też</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/super">super()</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/class"><code>class</code> expression</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/class"><code>class</code> declaration</a></li> + <li><a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a></li> +</ul> |