DifferentPseudonym
DifferentPseudonym

Reputation: 1024

node.js - Creating instance of a class directly from require

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?

Upvotes: 13

Views: 6401

Answers (1)

jperezov
jperezov

Reputation: 3171

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");

Upvotes: 16

Related Questions