Konstruktor
Konstruktor jest specjalną metodą tworzenia i inicjowania obiektu utworzonego w klasie.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Składnia
constructor([arguments]) { ... }
Opis
Konstruktor umożliwia zdefiniowanie inicjalizacji obiektu, która musi się wykonać, zanim będzie można wywołać metody obiektu.
class Person {
constructor(name) {
this.name = name;
}
introduce() {
console.log(`Hello, my name is ${this.name}`);
}
}
const otto = new Person('Otto');
otto.introduce();
Jeśli niestandardowy konstruktor nie został podany, to domyślny konstruktor będzie użyty. Dla klas bazowych konstruktor domyślny jest pusty:
constructor() {}
Dla klas pochodnych domyślny konstruktor wywołuje konstruktor klasy nadrzędnej:
constructor(...args) {
super(...args);
}
Pozwala to na działanie takiego kodu:
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;
}
}
Klasa ValidationError
nie musi mieć niestandardowego konstruktora, ponieważ domyślny konstruktor wywołuje konstruktor klasy Error
.
Jeśli jednak klasa ValidationError
ma niestandardowy konstruktor, to musi on wywoływać konstruktor klasy nadrzędnej przy użyciu super
:
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;
}
}
Wewnątrz klasy może być tylko jedna metoda nazwana constructor
. Jeżeli constructor
wystąpi więcej niż jeden raz, to wygeneruje błąd SyntaxError
.
Przykłady
Używanie konstruktora
Fragment kodu pochodzi z classes sample (live demo).
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;
}
}
Inny przykład
W tym przykładzie klasa Square
jest zmieniona — ale konstruktor klasy Polygon
nadal jest wywoływany przy tworzeniu nowej instancji klasy Square
.
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
Specyfikacje
Specyfikacja | Status | Komentarz |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Constructor Method' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'Constructor Method' in that specification. |
Living Standard |
Kompatybilność
BCD tables only load in the browser