Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS: extend Class and __construct method

NodeJS: extend Class and __construct method

Problem

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);
Problem courtesy of: Marcelo Rodovalho

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.
Solution courtesy of: loganfsmyth

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS: extend Class and __construct method

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×