Module.exports: 不是一个构造函数的错误

5
有人能解释一下为什么第一个导出会抛出“is not a constructor”错误,而第二个导出可以工作吗?
// 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();

您正在导出一个名为“Person”的字段的对象。必须使用具有构造函数的函数或类来调用'new'。 - Jim B.
1个回答

6

因为第一次导出包含属性的对象:

  module.exports = { /*...*/ };

你无法构建该对象。但是,你可以获取“Person”属性并构建该对象:

 const Person = require("person").Person;
 new Person();

你也可以解构导入的对象:
 const { Person } = require("person");
 new Person();

......但是只有在那里导出其他东西才有意义,否则我会选择v2。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接