I am asking how to implement the virtual function in the javascript like C#, let's say
With this example below, I want to get a 'B' alert, not the 'A'.
function A() {
this.virtualFunction();
}
A.prototype.virtualFunction = function() {
alert('A');
};
//-------------------------------------
function B() {}
B.prototype = new A();
B.prototype.virtualFunction = function() {
alert('B');
};
var b = new B();
If we invoke the function after instanced, like this, then it is okay, but I need "inside the constructor"
var b = new B();
b.virtualFunction();
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 is a member function in the base class that we expect to redefine in derived classes. Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.
Why use virtual functions. We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual keyword before the function.
A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract. Classes containing pure virtual methods are termed "abstract" and they cannot be instantiated directly.
So, the first thing to realize is that JavaScript doesn't use the same semantics as C#. Trying to get it to do so will cause you heartache; you're much better off learning how things are done in JS. In fact, most folks don't try to do a lot of inheritance type stuff in JS, but instead favor composition (which is actually a best practice in all OO languages I'm familiar with).
That said, there's a few improvements you could make to your code.
function A() {
this.virtualFunction();
}
A.prototype.virtualFunction = function() {
alert('A');
};
//-------------------------------------
function B() {
A.call(this);
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
B.prototype.virtualFunction = function() {
alert('B');
};
var b = new B();
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