Абстракция
Пример до классов JS
function vehicleFactory() {
return {
drive() {
throw new Error("This method should be overridden.");
},
};
}
const car = vehicleFactory();
car.drive = function () {
return "Driving a car!";
};
console.log(car.drive());
Пример на классах JS
// имитация абстрактных классов в JavaScript
class AbstractClass {
constructor() {
if (new.target === AbstractClass) {
throw new Error("Cannot instantiate an abstract class directly.");
}
}
abstractMethod() {
throw new Error("Abstract method has no implementation.");
}
}
class ConcreteClass extends AbstractClass {
constructor() {
super();
}
abstractMethod() {
return "Concrete implementation of an abstract method.";
}
}
try {
const instance = new AbstractClass(); // Это вызовет ошибку
} catch (e) {
console.log(e.message);
}
const concrete = new ConcreteClass();
console.log(concrete.abstractMethod());