3

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.

delliottg
  • 3,950
  • 3
  • 38
  • 52

1 Answers1

4

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).

djfdev
  • 5,747
  • 3
  • 19
  • 38
  • That's [pretty much equivalent](https://stackoverflow.com/q/3034941/1048572) to the `var ow = new (require('./ourWidget'))` which the OP was already using – Bergi Feb 15 '18 at 00:10
  • 1
    Actually making the change to this syntax worked perfectly. Thank you! – delliottg Feb 15 '18 at 23:17
  • @Bergi No, the Op was using (require('foo')()) and your comment uses (require('foo)) when the answer above uses (require('foo'))() . The first executes the require, yours doesn't at all (just wraps the object) and the right way executes the wrapped object. New operates on the result. – rainabba Jan 31 '22 at 21:51
  • @rainabba The OP wrote "*I've also tried this: `var ow = new (require('./ourWidget')());`*", but they were originally using `var ow = new (require('./ourWidget'));` (or the same with a temporary `ourWidget` variable). Which is equivalent to what this answer is suggesting. – Bergi Jan 31 '22 at 22:26
  • @rainabba Not sure what you mean by "*just wraps the object*". `new` doesn't wrap anything, it constructs an instance of the operand function. The arguments parenthesis are optional. – Bergi Jan 31 '22 at 22:29