Extends class but cannot access subclass function

Below is my javascript code

function extend(Child, Parent) { var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; } function BController (){ } function AController (){ BController.call(this); } AController.prototype.dosomething=function(){ } 

if i call

  var g=new AController(); g.dosomething (); 

everything is fine. But if I call (I hope AContronller inherits BController)

  extend(AController,BController); var g=new AController(); g.dosomething (); 

he always reports

 g.dosomething is not a function 

Method 2: if I change the Acontroller as

 function AController ( ){ this.dosomethingNew=function(){ } } 

and call

  extend(AController,BController); var g=new AController(); g.dosomethingNew (); 

everything will be fine.

Your comment is welcome.

+4
source share
1 answer

You placed the bell in the wrong place. While the extension is being called, you are rewriting the entire ACcontroller prototype and you are losing dosomething in the process.

Instead, you want to call the extension before you add all the AController-specific stuff.

So it should look like this:

 function BController ( ){ } // <--- no semicolon after function declarations function AController (){ BController.call(this); } // <---- remove here too extend(AController, BController); // <---- HERE //Now AController prototype is a new object whose prototype //is BController prototype, thereby inheriting everything from //BController. Now you may add specific stuff to AController AController.prototype.dosomething = function(){ }; 

Here's a working demo

+2
source

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


All Articles