Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

util.inherits for custom subclasses in Node?

Tags:

node.js

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?

like image 868
sak Avatar asked Feb 19 '23 02:02

sak


1 Answers

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.

like image 81
juandopazo Avatar answered Feb 28 '23 03:02

juandopazo