Answer the question
In order to leave comments, you need to log in
Abstraction in JavaScript?
Good afternoon.
Soon there will be an interview for the position of Trainee / Junior JS developer and they will ask about OOP. I understand the first three principles:
Answer the question
In order to leave comments, you need to log in
Remember how your parents forced you to play the piano or learn poetry?.. So, Abstract classes, like many parents, do not even know why the child-descendant will need it, and how he will use it, but we are sure that NECESSARY! Those. such classes contain abstract methods, which are a declaration of a method without the implementation itself, like a candy wrapper without candy, thereby obliging the child to implement this method. As in life, where parents often shift their unrealized dreams onto their children ...
In such a jokingly serious form, we touched on the topic of abstract classes and family relations, as a way to understand ... both? .. But seriously, of course, there should not be random methods in programming, and any methods and properties are part well-thought-out class hierarchy, which, like a family tree, can provide opportunities to expand the functionality from generation to generation. And abstract classes, and even more abstract ones - interfaces (interface - does not contain implementations at all), help the programmer not to lose, not to forget to implement the common skills necessary for all descendants in life, without which the individual will die, and with it the application.
Excuse me, what do you mean by abstraction in js?
There are, for example, abstract classes. You can read about this in books about patterns. Abstract classes, let me not be thrown tomatoes for inaccuracy, are classes whose methods may not be described.
class Animal {
constructor({name, age}) {
if (this.constructor.name === 'Animal') {
throw new Error(`${this.constructor.name}: can not create instance of abstract class`);
}
this.name = name;
this.age = age;
}
name() {
return this.name;
}
age() {
return this.age;
}
/*
* Абстрактный метод
*/
talk() {}
}
class Dog extends Animal {
talk() {
console.log('Bark!')
}
}
const animal = new Animal({
name: 'Jack',
age: 5
}); // выбросит ошибку
const dog = new Dog({
name: 'Jack',
age: 5
});
dog.talk(); // Bark!
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question