Nodejs module extends with other module

Tags: ,



Hi i have parent module like this.

// usermgmt.js

var usermgmt = function () {};

usermgmt.prototype.test = function () {
    return "test";
};

usermgmt.private = function () {
    return "private";
};

module.exports = new usermgmt();

and a Child prototype class like this.

// authentication.js
var usermgmt = require('./usermgmt');

var authentication = function () {};

authentication.prototype.callParent = function () {
    usermgmt.private();
};

module.exports = new authentication();

How i implement inheritance? I searched by google but no solution works for me.

Answer

As @jfriend00 said, I write these functions with class keyword which is a syntactic sugar for your code!

usermgmt.js

// usermgmt.js

class usermgmt {
  constructor() {

  }

  test() {
    return "test";
  }

  private() {
    return "private";
  }
}

module.exports = usermgmt;

Write authentication like this.

authentication.js

// authentication.js
var Usermgmt = require('./usermgmt.js');

class authentication extends Usermgmt {
  constructor() {
    super();
  }

  callParent() {
    console.log(this.private());
  }

  authFunction() {
    console.log(':: authFunction ::');
    this.callParent();
  }
}

module.exports = authentication;

And usage for authentication will be:

var Authentication = require('./authentication.js');

let auth = new Authentication();

auth.callParent();

auth.authFunction();

console.log(auth.test());

1) Use class and extends syntax which is easier.

2) Return Class and not its instance



Source: stackoverflow