Code Example 1: extends
❓ Что произойдёт при вызове child.greet()? Откуда Child берёт этот метод?
class Parent {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Привет, я ${this.name}`);
}
}
class Child extends Parent {
}
const child = new Child('Алексей');
child.greet();
Code Example 2: super keyword
❓ Что выведет dog.speak()? Для чего используется super в конструкторе и в методе?
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} издаёт звук`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
super.speak();
console.log(`${this.name} лает`);
}
}
const dog = new Dog('Рекс', 'Овчарка');
dog.speak();
Code Example 3: Vehicle hierarchy
❓ Что выведут вызовы car.start(), car.getInfo(), bike.wheelie()? Как работает наследование методов start() и stop()?
class Vehicle {
constructor(brand, model) {
this.brand = brand;
this.model = model;
this.isRunning = false;
}
start() {
this.isRunning = true;
console.log(`${this.brand} ${this.model} запущен`);
}
stop() {
this.isRunning = false;
console.log(`${this.brand} ${this.model} остановлен`);
}
getInfo() {
return `${this.brand} ${this.model}`;
}
}
class Car extends Vehicle {
constructor(brand, model, doors) {
super(brand, model);
this.doors = doors;
this.gear = 'P';
}
shift(gear) {
this.gear = gear;
console.log(`Переключено на ${gear}`);
}
getInfo() {
return `${super.getInfo()}, ${this.doors} двери`;
}
}
class Motorcycle extends Vehicle {
constructor(brand, model, type) {
super(brand, model);
this.type = type;
}
wheelie() {
if (this.isRunning) {
console.log(`${this.brand} делает вилли!`);
} else {
console.log('Сначала заведите мотоцикл');
}
}
}
const car = new Car('Toyota', 'Camry', 4);
car.start();
car.shift('D');
console.log(car.getInfo());
const bike = new Motorcycle('Yamaha', 'R1', 'sport');
bike.start();
bike.wheelie();
Code Example 4: Method overriding
❓ Что выведут rect.describe() и circle.describe()? Как работает полиморфизм в этом примере?
class Shape {
constructor(color) {
this.color = color;
}
getArea() {
return 0;
}
describe() {
return `Фигура цвета ${this.color} с площадью ${this.getArea()}`;
}
}
class Rectangle extends Shape {
constructor(color, width, height) {
super(color);
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
getArea() {
return Math.PI * this.radius ** 2;
}
}
const rect = new Rectangle('синий', 10, 5);
const circle = new Circle('красный', 7);
console.log(rect.describe());
console.log(circle.describe());
Code Example 5: instanceof
❓ Что вернёт каждый instanceof? Как JavaScript определяет принадлежность к классу?
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
const dog = new Dog();
console.log(dog instanceof Dog);
console.log(dog instanceof Animal);
console.log(dog instanceof Cat);
Code Example 6: this before super()
❓ Почему обращение к this до вызова super() вызывает ошибку?
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
// this.age = age;
super(name);
this.age = age;
}
}
Code Example 7: super in arrow functions
❓ Что вернёт child.greet()? Почему super работает внутри стрелочной функции?
class Parent {
greet() {
return 'Привет от родителя';
}
}
class Child extends Parent {
greet() {
const arrow = () => super.greet();
return arrow() + ' и от ребёнка';
}
}
const child = new Child();
console.log(child.greet());
Code Example 8: Static method inheritance
❓ Что вернут Parent.create() и Child.create()? Как работает this в статическом методе?
class Parent {
static create() {
return new this();
}
static description = 'Базовый класс';
}
class Child extends Parent {
static description = 'Дочерний класс';
}
const parent = Parent.create();
const child = Child.create();
console.log(Parent.description);
console.log(Child.description);
Code Example 9: Inheritance vs Composition
❓ В чём разница между этими двумя подходами? Когда лучше использовать каждый из них?
Наследование:
class Animal {
eat() { console.log('Ест'); }
}
class Dog extends Animal {
bark() { console.log('Лает'); }
}
const dog = new Dog();
dog.eat();
dog.bark();
Композиция:
class Engine {
start() { console.log('Двигатель запущен'); }
}
class Car {
constructor() {
this.engine = new Engine();
}
start() {
this.engine.start();
console.log('Машина готова к поездке');
}
}
const car = new Car();
car.start();