Util.inherits for custom subclasses in Node?

I am trying to implement very simple inheritance for some custom classes in node. I am doing something like this:

function MyClass() { this.myFunction = function(){ //do something } } function MySubclass(){ this.myOtherFunction = function(){ //do something else } } util.inherits(MySubclass, MyClass) console.log(MySubclass.super_ === MyClass); // true var x = new MySubclass() console.log(x instanceof MyClass); // true x.myFunction() 

And if I run this, I will get the error:

 TypeError: Object #<MySubclass> has no method 'myFunction' 

This exact template works great for inheriting from events. EventEmitter. Doesn't this just work for custom classes, or is there something I am missing?

+4
source share
1 answer

util.inherits sets up a prototype chain. What you are missing is to call the super constructor to add material to this . Here's how to do it:

 function MyClass() { this.myFunction = function() { // Do something }; } MyClass.prototype.doFoo = function () { }; function MySubclass() { // This is doing the same as MyClass.apply(this, arguments); MySubclass.super_.apply(this, arguments); this.myOtherFunction = function() { // Do some other thing }; } util.inherits(MySubclass, MyClass); MySubclass.prototype.doBar = function() { }; var x = new MySubclass(); x.myFunction(); x.myOtherFunction(); x.doFoo(); x.doBar(); 

You can still transfer these methods to each prototype.

+8
source

All Articles