util.inherits for custom subclasses in Node?
node.js
Solution
`util.inherits` only sets up the prototype chain. What you're missing is to call the super constructor so that it adds stuff 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 may still want to move those methods to each prototype.
Problem
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?