How to apply virtual function in javascript
javascript, oop, virtual-functions
Solution
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.
Problem
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.