Search code examples
phpnode.jsclassmethodsconstruct

NodeJS: extend Class and __construct method


Im migrating my system from PHP to NodeJS, and I have the following doubt:

In PHP, I have the class

class Users extends Groups {
    function __construct(){
        parent::__construct();
        //do something
    }
}

But, how to do the same in Javascript/NodeJS (ExpressJS)? I think is this to extends, but how I define the __construct method? What is the name of the method that will be called in the start of Class instance like in PHP?

var utils = require('utils');
var Groups = require('./groups.js');
var Users = function(){
    //where is the __construct??
};
util.inherits(Users, Groups);

Solution

  • There is not parent construct specifically, so it is up to you to somehow call the parent constructor.

    inherits adds a super_ property to it's first argument

    Users.super_ = Groups;
    

    so you can call the parent constructor like this:

    Users.super_.call(this); // Can pass arguments to function as more params.
    
    // OR
    Users.super_.apply(this, arguments); // Pass all arguments through.
    

    or you can also reference the parent constructor directly:

    Groups.call(this); // Can pass arguments to function as more params.
    
    // OR
    Groups.apply(this, arguments); // Pass all arguments through.