How to apply virtual function in javascript
Asked Answered
C

3

6

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.

Cimex answered 19/6, 2012 at 7:58 Comment(3)
I think you meant virtual/override, not abstract.Altdorfer
Yes, the base's function must be a virtual function so that the inherit class can override it.Cimex
I'm not sure I understand. Just remove BaseClass.call(this); line and it works, since this.talk=... overrides the base method. Or you can start MyClass with BaseClass.call(...) (at the begining, not the end). But if you are using call then there is no need for defining prototype.Rotl
L
7

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.

Lynettalynette answered 19/6, 2012 at 8:9 Comment(0)
R
4

You are overriding your function by doing BaseClass.call(this);

function MyClass() {
    //BaseClass.call(this); // Not really necessary unless you run code inside your base class
    this.talk = function() {
        alert("I'm MyClass");
    }
};

This would make your code work. The MyClass.prototype = new BaseClass(); should make the hello function available on your a object.

Rattlebox answered 19/6, 2012 at 8:9 Comment(0)
R
4

The problem is that you are actually defining private instance methods, in both the MyClass and the BaseClass constructors. This overrides the prototype method lookup, since the talk methods are not located in the prototype but are actual instance properties, and the BaseClass constructor is invoked after the MyClass constructor, thus overwriting the talk property.

Demonstration with actual prototype inheritance.

Rashidarashidi answered 19/6, 2012 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.