Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a new Node object from a require in one line? [duplicate]

We have a Node.js widget that gets exported like so:

module.exports = ourWidget;

I then import it into our server.js like so:

var ourWidget = require('./ourWidget');
var ow = new ourWidget;

This works as expected, but could it be done in a single line? EG:

var ow = new (require('./ourWidget'));

Which doesn't work, I've also tried this:

var ow = new (require('./ourWidget')());

Both of which resembles the code in this SO question: How does require work with new operator in node.js?, but both fail as soon as I try to run the code.

like image 746
delliottg Avatar asked Oct 16 '25 16:10

delliottg


1 Answers

You can achieve this by shifting the function call to outside of the wrapping parens:

var ow = new (require('./ourWidget'))()

But keep in mind you now have no way of accessing the original widget constructor (this may or may not be a bad thing in your case).

like image 149
djfdev Avatar answered Oct 18 '25 08:10

djfdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!