13

I have a class in a seperate file. I need to create an instance of it in another file. I tried this:

var connection = new require('./connection.js')("ef66143e996d");

But this is not working as I wanted. Right now I am using this as a temporary solution:

var Connection = require('./connection.js'); 
connection = new Connection("ef66143e996d");

Two Questions;

First, why doesn't that work.
Second, how can I accomplish this with a one-liner?

DifferentPseudonym
  • 1,004
  • 1
  • 12
  • 28

1 Answers1

16

The new keyword applies itself on the first function it comes across. In this case, that happens to be require. Wrapping the statement in parentheses will expose the correct function:

var connection = new (require('./connection.js'))("ef66143e996d");
jperezov
  • 3,041
  • 1
  • 20
  • 36
  • 1
    This works, ok. But I invoked the `require` with `("ef66143e996d")`. Why doesn't `new` apply to the function returned from `require('./connection.js')("ef66143e996d")`. This must be the first function it comes across. – DifferentPseudonym Nov 19 '15 at 18:21
  • 1
    When running `new require('connection')()`, require is the first function it comes across. It's being evaluated left-to-right. Wrapping `require('connection')` in parentheses makes it so that whatever the parentheses resolves to is what `new` is being applied to. – jperezov Nov 19 '15 at 18:41
  • 1
    To clarify, assuming `require('./connection.js')` exposes the function `Connection`, the `Connection` function _isn't_ exposed until the `require` function is invoked. The `new` keyword would trigger before the `require` function _unless_ the function is wrapped in parentheses. It is the same reason `3 * 2 + 1 = 7`, but `3 * (2 + 1) = 9`. Think of the `new` keyword as the multiplication in this example--it has a higher precedence. – jperezov Nov 19 '15 at 18:49
  • 1
    Thanks a lot for your explanation, you made things clearer in mind. – DifferentPseudonym Nov 19 '15 at 19:07