Javascript 设置类值时无法设置未定义的属性
这是我的代码,我试图将类值设置为db.db('mydb'),以便在下面的其他函数中使用Javascript 设置类值时无法设置未定义的属性,javascript,node.js,mongodb,class,Javascript,Node.js,Mongodb,Class,这是我的代码,我试图将类值设置为db.db('mydb'),以便在下面的其他函数中使用 class Database { constructor() { this.db_url = "mongodb://127.0.0.1:27017/"; let mongodb = require("mongodb").MongoClient; mongodb.connect(this.db_url, { useU
class Database {
constructor() {
this.db_url = "mongodb://127.0.0.1:27017/";
let mongodb = require("mongodb").MongoClient;
mongodb.connect(this.db_url, { useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
this.dbo = db.db('mydb');
})
}
}
我试图设置class=db.db('mydb')的dbo值,但收到了这个错误
this.dbo = db.db('mydb')
^
TypeError: Cannot set property 'dbo' of undefined
但是,当我附加
console.log(db.db('mydb'))
时,它仍然正常打印出来,正如错误所说:TypeError:cannotset-set-property'dbo'of undefined
,这个
在回调函数中未定义。我所理解的是,因为“上下文”已更改(您在回调函数中),当您在构造函数中时,这不再是同一件事。你可以参考以获得正式的解释
在您的情况下,您可以使用一个变量来保存this
class Database {
constructor() {
this.db_url = "mongodb://127.0.0.1:27017/";
var self = this; // add variable self which refer to the same object with this
let mongodb = require("mongodb").MongoClient;
mongodb.connect(this.db_url, { useUnifiedTopology: true }, function(err, db) {
if (err) throw err;
self.dbo = db.db('mydb'); // replace this by self
})
}