I’m 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 get the error:
TypeError: Object #<MySubclass> has no method 'myFunction'
This exact pattern works perfectly well for inheriting from events.EventEmitter. Does it just not work for custom classes, or is there something I’m missing?
util.inheritsonly sets up the prototype chain. What you’re missing is to call the super constructor so that it adds stuff tothis. Here’s how to do it:You may still want to move those methods to each prototype.