Для создания подклассов в JavaScript вы можете использовать концепцию прототипного наследования. Есть несколько способов сделать это, но я объясню два распространенных подхода: использование синтаксиса class
, представленного в ECMAScript 2015 (ES6), и использование цепочки прототипов.
-
Использование синтаксиса
class
:class ParentClass { // Parent class constructor constructor(name) { this.name = name; } // Parent class method sayHello() { console.log(`Hello, ${this.name}!`); } } class ChildClass extends ParentClass { // Child class constructor constructor(name, age) { super(name); // Call the parent class constructor this.age = age; } // Child class method introduce() { console.log(`My name is ${this.name} and I'm ${this.age} years old.`); } } // Creating an instance of the child class const child = new ChildClass("Alice", 10); child.sayHello(); // Output: Hello, Alice! child.introduce(); // Output: My name is Alice and I'm 10 years old.
-
Использование цепочки прототипов:
function ParentClass(name) { this.name = name; } ParentClass.prototype.sayHello = function () { console.log(`Hello, ${this.name}!`); }; function ChildClass(name, age) { ParentClass.call(this, name); this.age = age; } // Establishing the prototype chain ChildClass.prototype = Object.create(ParentClass.prototype); ChildClass.prototype.constructor = ChildClass; ChildClass.prototype.introduce = function () { console.log(`My name is ${this.name} and I'm ${this.age} years old.`); }; // Creating an instance of the child class const child = new ChildClass("Alice", 10); child.sayHello(); // Output: Hello, Alice! child.introduce(); // Output: My name is Alice and I'm 10 years old.
Это всего лишь два примера создания подклассов в JavaScript. В зависимости от ваших конкретных требований вы можете использовать и другие варианты и шаблоны, например фабричные функции, композицию или миксины.