Ayfri
Ayfri

Reputation: 637

Make an instance of a class that is in an another file without creating a new variable

I have a file that contains this :

// filename "Test1"
module.exports = class Test {
    constructor() {
        console.log('Instancied !');
    }
}

I have a second file that contains this

// filename "Test2"
const Test = require('./Test1');

const testInstance = new Test();

Is there a way to simplify this to create the class in the same line as the require?
This doesn't works but I'm thinking that is can looks like this : const testInstance = new (require('./Test1'));

Upvotes: 2

Views: 151

Answers (2)

Mureinik
Mureinik

Reputation: 311808

require('./Test1') returns the definition of the class. So you have the right idea, you're just missing a pair of ():

const testInstance = new (require('./Test1'))();

Upvotes: 3

technophyle
technophyle

Reputation: 9149

This is the best I can think of:

// Test1
class Test {
    constructor() {
        console.log('Instancied !');
    }
}

module.exports = () => new Test();

// Test2
const testInstance = require('./Test1')();

Does this solve your problem?

Upvotes: 2

Related Questions