我正在尝试实例化一个导出的类,但出现以下错误:
TypeError: Cannot set property '_db' of undefined
我是如何创建和导出类的:
const mongodb = require('mongodb').MongoClient
const url = 'mongodb://localhost/via'
const collection = 'images'
module.exports = class DB {
constructor() {
mongodb.connect(url, function(err, db) {
if (err) throw err
this._db = db.db('via') //Error line
this._db.createCollection(collection, function(err, res) {
if (err) throw err
console.log(`Collection ${collection} created successfully.`)
})
})
}
}
我是如何实例化的:
const db = require('../db/images')
let database = new db();
我试过在使用它之前创建变量,但无济于事。我做错了什么?
最佳答案
这里的问题是你的构造函数在你调用 mongodb.connect
的地方使用普通函数回调 -> function(err, db)
这意味着函数内部的任何东西this
不会指向您的类。
一个简单的解决方案是使用箭头函数,将 function(err, db) {
替换为 (err, db) => {
就我个人而言,我不是箭头函数的忠实粉丝,在某些方面我认为它类似于 with
语句,很容易失去上下文。因此,与箭头函数和普通函数一起使用的另一种方法是捕获作用域。
例如->
module.exports = class DB {
constructor() {
const thisDB = this;
mongodb.connect(url, function(err, db) {
if (err) throw err
thisDB._db = db.db('via') //Error line
thisDB._db.createCollection(collection, function(err, res) {
if (err) throw err;
//bonus, thisDB will work here too.
console.log(`Collection ${collection} created successfully.`)
})
})
}
}
上面很明显 thisDB
也指向什么,当进行更深层次的回调时,它仍然有效,如上所示,我在上面提到了 bonus,thisDB 也可以在这里工作
关于javascript - 实例化导出类的属性时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49481716/