In C#, we have concept about abstract method, and how to apply this in Javascript. Example, I have an example:
function BaseClass() {
this.hello = function() {
this.talk();
}
this.talk = function() {
alert("I'm BaseClass");
}
};
function MyClass() {
this.talk = function() {
alert("I'm MyClass");
}
BaseClass.call(this);
};
MyClass.prototype = new BaseClass();
var a = new MyClass();
a.hello();
How the function hello() in BaseClass call the function do() from MyClass when the object is an instance of MyClass. The alert result must be "I'm MyClass". Please help me. Thanks.
Description. The virtual modifier is used to declare a method or property as a virtual method or property, respectively. Virtual methods can be overridden using the override or final modifier. By default, methods are non-virtual and are resolved at compile time.
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer.
You might want to call the "Base" constructor first:
function MyClass() {
BaseClass.call(this);
this.talk = function() {
alert("I'm MyClass");
}
}
otherwise BaseClass.talk
will overwrite MyClass.talk
.
As a side note, using the concept of "classes" in javascript is rather counterproductive, because this is not how this language works. JS uses prototypal inheritance, that is, you derive new objects from other objects, not from "classes". Also, every function in JS is "virtual" in C++ sense, because its this
pointer depends on how the function is called, not on where it's defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With