Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply virtual function in javascript

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.

like image 327
Leo Vo Avatar asked Jun 19 '12 07:06

Leo Vo


People also ask

What is virtual function in Javascript?

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.

What is a virtual function give an example?

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.

What is a virtual function and how is it implemented?

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.


1 Answers

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.

like image 148
georg Avatar answered Oct 06 '22 23:10

georg