How do I call the function named "method()" belonging to class A and not to class B?
class A
{
constructor()
{
}
metodo()
{
this.virtual();
}
virtual()
{
console.log("Original");
}
}
class B extends A
{
constructor()
{
super();
}
metodo()
{
}
virtual()
{
console.log("Sustituto");
}
}
b = new B();
b.metodo();
The desired output obtained should be this:
Sustituto
If you want to get Substitute on the output, simply remove the method
metodo
and the parent function will call the onevirtual
from class B.Also, you are missing the call
super()
in the constructor of class B.I will explain a couple of concepts. Although JS is not strong in object-oriented programming, it does give you the ability to declare and/or use classes. You created two classes, A and B, the last one extends from A. When one class extends from another, it automatically inherits everything, in this case it inherits all the methods. When you declare the method
metodo()
in class B, what you do is override it , so it is no longer the same as in class A. The fixed code would look like this:Although the method does not exist in class B
metodo()
, it could be called since it is inherited.Hope this can help you.