0

Why is the following code gives me an error?

// In Foo.js
class Foo {
    constructor(a) {
        this.a = a;
    }
}

module.exports = Foo

// In Index.js
var foo = new require('path/Foo.js')('param');

This gives me Class constructor Foo cannot be invoked without 'new'.

Thanks.

2
  • Because the code shown is invoking the require function with new rather than your constructor? Commented Dec 5, 2017 at 2:46
  • @nnnnnn I forgot to do module.exports at the end. If i do this, require('path/Foo.js) returns Foo class isn't it? Commented Dec 5, 2017 at 2:48

1 Answer 1

3

I believe that in your code the new operator is applied to the require() function, not to what require() returns. That is, this:

var foo = new require('path/Foo.js')('param');

...is like doing this:

var foo = ( new require('path/Foo.js') )('param');

...or:

var temp = new require('path/Foo.js');
var foo = temp('param');

Try the following instead, so that new is applied to your class:

var Foo = require('path/Foo.js');
var foo = new Foo('param');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I thought "require("path/Foo.js")" is same as "Foo".

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.