Reputation: 12934
Can someone explain why the first export throws a is not a constructor
error, while the second export works?
// Throws a `is not a constructor` error
module.exports = {
Person: function () {
constructor()
{
this.firstname;
this.lastname;
}
}
}
// Works
class Person {
constructor()
{
this.firstname = '';
this.lastname = '';
}
}
module.exports = Person;
// Usage:
const Person = require("person");
let person = new Person();
Upvotes: 5
Views: 5889
Reputation: 138234
Because the first time you actually export an object containing a property:
module.exports = { /*...*/ };
And you can't construct that object. However you could get the Person property and construct that:
const Person = require("person").Person;
new Person();
You could also destructure the imported object:
const { Person } = require("person");
new Person();
... but that only makes sense if there are other things exported there otherwise I would go with v2.
Upvotes: 6