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?

1 Answer 1

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");
4
  • 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. Commented Nov 19, 2015 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
    Commented Nov 19, 2015 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
    Commented Nov 19, 2015 at 18:49
  • 1
    Thanks a lot for your explanation, you made things clearer in mind. Commented Nov 19, 2015 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.