【问题标题】:TypeError: Database is not a constructor when initializing constructorTypeError:初始化构造函数时数据库不是构造函数
【发布时间】:2018-03-06 15:42:46
【问题描述】:

我有一个如下所示的数据库对象 (database.js):

//create the database 
function Database(host, dbuser, dbpassword){
    this.host = host;
    this.dbuser = dbuser;
    this.dbpassword = dbpassword;
    this.connection = null;
}

Database.prototype = {
    connection: function(){
        this.connection = mysql.createConnection({
            host: host,
            user: dbuser
        });
    },
    createDatabase: function(){...};

然后我使用 require 语句将此对象导入到我的主 app.js 中

var db = require('./database.js');

但是,当我尝试构造我的数据库对象时,我得到一个 TypeError Database is not a constructor

var connection = new db('localhost','root');
connection.connection();

我在这里做错了什么?我阅读了原型,似乎我在那个部门并没有缺少任何东西,所以它似乎与我的需求声明有关?

【问题讨论】:

  • 因为node.js现在默认支持ES6,所以使用class。它会让你的代码更容易,你会避免这样的错误。
  • 但是这个原型有什么原因不能工作吗?我必须阅读课程,但我认为原型仍然受支持......
  • 您是如何将Database 导出到您的文件database.js 中的?
  • 我做了 exports.Database = Database;
  • {host: host, user: dbuser}{host: this.host, user: this.dbuser}

标签: javascript node.js


【解决方案1】:

要导出您的Database "class" 使用

module.exports = Database;

并使用

var Database = require('./database.js');

new Database(...);

Here you have a good tutorial about how to use export/require


仍然强烈建议升级到 ES6。

【讨论】:

  • 啊,非常感谢!工作完美!在 Node 上的工作仍然不确定,但这似乎解决了我的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 1970-01-01
  • 2019-08-14
  • 2017-05-09
相关资源
最近更新 更多