node.js - 模块.exports : is not a constructor error

标签 node.js ecmascript-6

有人可以解释为什么第一次导出抛出 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();

最佳答案

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

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

而且您无法构造该对象。但是,您可以获得 Person 属性并构造它:

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

您还可以解构导入的对象:

 const { Person } = require("person");
 new Person();

...但这只有在导出其他内容时才有意义,否则我会选择 v2。

关于node.js - 模块.exports : is not a constructor error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53105744/

相关文章:

node.js - 如何使用 Node.js 即时创建图像?

javascript - 如何在 Node.js 中添加 promise.all Sequelize findOrCreate 循环?

JavaScript 符号并没有阻止对象中的名称冲突

javascript - 如何获取数组中最频繁/出现的元素

javascript - 当需要从类中回调时,将 React 常量移至其自己的文件中

javascript - 在 ES6 中自动将参数设置为实例属性

node.js - Firebird - getaddrinfo ENOTFOUND

android - V8 内存使用

node.js - 如何使用Nodejs Express获取发送请求的客户端的公共(public)IP地址?

javascript - ReduceRight 与 Reduce