How to apply virtual function in javascript

In C #, we have a concept about an 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 hello () function in BaseClass calls the do () function of MyClass when the object is an instance of MyClass. The result of the warning should be "I'm MyClass." Please help me. Thanks.

+6
source share
3 answers

You can call the Base constructor first:

 function MyClass() { BaseClass.call(this); this.talk = function() { alert("I'm MyClass"); } } 

otherwise BaseClass.talk overwrite MyClass.talk .

As a side note, using the concept of β€œclasses” in javascript is quite counterproductive because it is not how this language works. JS uses prototype inheritance, that is, you retrieve new objects from other objects, not from "classes". In addition, each function in JS is β€œvirtual” in the sense of C ++, because its this pointer depends on how the function is called, and not on where it is defined.

+7
source

You cancel your function by executing 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 will make your code work. MyClass.prototype = new BaseClass(); should make the hello function available to your object a .

+4
source

The problem is that you are actually defining private instance methods in the MyClass and BaseClass . This overrides the search for the prototype method, since the talk methods are not in the prototype, but are the actual properties of the instance, and the BaseClass constructor BaseClass called after the MyClass constructor, thereby overwriting the talk property.

Demonstration with the actual inheritance of the prototype.

+4
source

Source: https://habr.com/ru/post/918445/


All Articles