From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../reference/classes/constructor/index.html | 205 +++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 files/ru/web/javascript/reference/classes/constructor/index.html (limited to 'files/ru/web/javascript/reference/classes/constructor') diff --git a/files/ru/web/javascript/reference/classes/constructor/index.html b/files/ru/web/javascript/reference/classes/constructor/index.html new file mode 100644 index 0000000000..7d7fe14e82 --- /dev/null +++ b/files/ru/web/javascript/reference/classes/constructor/index.html @@ -0,0 +1,205 @@ +--- +title: constructor +slug: Web/JavaScript/Reference/Classes/constructor +tags: + - ECMAScript 2015 + - ES6 + - JavaScript + - Классы +translation_of: Web/JavaScript/Reference/Classes/constructor +--- +
{{jsSidebar("Classes")}}
+ +
constructor - специальный метод, служащий для создания и инициализации объектов, созданных с использованием class.
+ +

Синтаксис

+ +
constructor([arguments]) { ... }
+ +

Описание

+ +

Конструктор позволяет произвести начальную инициализацию, которая должна быть выполнена до того, как остальные методы вызваны.

+ +
class Person {
+
+  constructor(name) {
+    this.name = name;
+  }
+
+  introduce() {
+    console.log(`Hello, my name is ${this.name}`);
+  }
+
+}
+
+const otto = new Person('Отто');
+
+otto.introduce();
+ +

Если вы не определили метод constructor, то будет использован конструктор по умолчанию. Если ваш класс базовый, то конструктор по умолчанию пустой:

+ +
constructor() {}
+ +

Если ваш класс является производным классом, конструктор по умолчанию вызывает родительский конструктор, передавая любые аргументы, которые были предоставлены:

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Это позволяет работать код:

+ +
class ValidationError extends Error {
+
+  printCustomerMessage() {
+    return `Проверка не удалась :-( (подробности: ${this.message})`;
+  }
+
+}
+
+try {
+  throw new ValidationError("Не правильный номер телефона");
+} catch (error) {
+   if (error instanceof ValidationError) {
+    console.log(error.name); // Это Error вместо ValidationError!
+    console.log(error.printCustomerMessage());
+  } else {
+    console.log('Не известная ошибка', error);
+    throw error;
+  }
+}
+ +

ValidationError классу не нужен явный (explicit) конструктор, потому что не требуется инициализация. Затем конструктор по умолчанию позаботится о инициализации родительского класса Error переданным ему аргументом.

+ +

Однако, если определен ваш собственный конструктор и ваш класс является производным от какого-либо родительского класса, то вы должны явно объявить конструктор родительского класса, используя super. К примеру:

+ +
class ValidationError extends Error {
+
+  constructor(message) {
+    super(message);  // вызов конструктора родительского класса
+    this.name = 'ValidationError';
+    this.code = '42';
+  }
+
+  printCustomerMessage() {
+     return `Проверка не удалась :-( (подробности: ${this.message}, code: ${this.code})`;
+  }
+
+}
+
+try {
+  throw new ValidationError("Не правильный номер телефона");
+} catch (error) {
+   if (error instanceof ValidationError) {
+    console.log(error.name); // Теперь это ValidationError!
+    console.log(error.printCustomerMessage());
+  } else {
+    console.log('Не известная ошибка', error);
+    throw error;
+  }
+}
+ +

В классе может быть только один метод с именем "constructor". Если класс содержит более одного constructor, будет сгенерировано исключение {{jsxref("SyntaxError")}}.

+ +

Примеры

+ +

Использование метода constructor

+ +

Данный фрагмент кода взят из classes sample (live demo).

+ +
class Square extends Polygon {
+  constructor(length) {
+    // Здесь вызывается конструктор родительского класса,
+    // в который передается length в качестве аргументов,
+    // соответствующим полям width и height класса Polygon
+    super(length, length);
+    // Заметка: В производном классе, super() должен вызываться перед тем как
+    // вы сможете использовать 'this'. Иначе будет сгенерировано исключение reference error.
+    this.name = 'Square';
+  }
+
+  get area() {
+    return this.height * this.width;
+  }
+
+  set area(value) {
+    this.area = value;
+  }
+}
+ +

Другой пример

+ +

Посмотрите на этот отрывок кода.

+ +
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
+ +

Здесь прототип Square класса изменен, но в то же время constructor предыдущего базового класса Polygon вызывается при создании нового экземпляра Square.

+ +

Constructors по умолчанию.

+ +

Если вы не определите метод constructor, будет использован constructor по умолчанию. Для базовых классов, constructor по умолчанию:

+ +
constructor() {}
+ +

Для производных классов, constructor по умолчанию:

+ +
constructor(...args) {
+  super(...args);
+}
+ +

Спецификация

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Изначальное определение.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}}
+ +

Совместимость с браузерами

+ + + +

{{Compat("javascript.classes.constructor")}}

+ +

Смотрите также

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