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

Module exporting with prototypes and export inheritance in node.js

Module exporting with prototypes and export inheritance in node.js

Problem

I have some questions about Module Exporting and their inheritance in node.

I know you can export a Module with

module.exports = function User(){
   // Lot of code
}

But, how could you add prototypes functions and get them exported as well? Is this automatic?

For example will this code be available to the exported user?

User.prototype.login = function (password) {
     // Much more code
}

And finally, if I require moduleA and Moduleb in the main script, will be able moduleB to use those objects or should I require it as well? What route should be used?

Problem courtesy of: Antonio Laguna

Solution

It's automatic, you don't need to do any magic, but I recommend you do module.exports = User; at the end of the file.

If you need moduleB to include something from moduleA you can either:

  • require moduleA inside moduleB
  • pass moduleB a parameter representing the object / function from module A when requiring it.
Solution courtesy of: alessioalex

Discussion

View additional discussion.



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

Share the post

Module exporting with prototypes and export inheritance in node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×