Javascript NodeJS/ES6:无法设置未定义的属性

Javascript NodeJS/ES6:无法设置未定义的属性,javascript,node.js,mongodb,scope,Javascript,Node.js,Mongodb,Scope,我使用NodeJS/ES6创建了一个MongoDB连接器类 class DBClient { constructor(host, port) { this.host = host; this.port = port this.dbConnection = null; } buildConnectionString() { return 'mongodb://' + this.host + ':' + th

我使用NodeJS/ES6创建了一个MongoDB连接器类

class DBClient {

    constructor(host, port) {
        this.host = host;
        this.port = port
        this.dbConnection = null;
    }

    buildConnectionString() {
        return 'mongodb://' + this.host + ':' + this.port;
    }

    connect() {
        var connectionString = this.buildConnectionString();
        console.log('[MongoDB] - Connecting to instance @ ' + connectionString);
        var DBConnection = MongoClient.connect(connectionString, function(error, db) {
            if (error) {
                console.log('[MongoDB] - Error connecting to instance');
                console.log(error);
            }
            else {
                console.log('[MongoDB] - Connection Successful');
                this.dbConnection = db;
            }
        });
    }
}
然后在不同的文件中创建,如下所示

var client = new DBClient('127.0.0.1', '1337');
client.connect();
当数据库连接到时,NodeJS在到达此位置时崩溃。dbConnection=db;,stating TypeError:无法设置未定义的属性“dbConnection”

我敢肯定,这与回调中的使用有关,这会破坏范围。但是我怎么才能避开这个问题呢?回调作用域中的任何操作都不会被隔离并且无法引用它吗


另外,作为一个附带问题,像我在构造函数中所做的那样初始化null属性是不是一种糟糕的代码实践?如果是这样的话,有什么更合适的方法呢?

事实上,如果您想保留您的范围,请使用lambda,例如:

var DBConnection = MongoClient.connect(connectionString, (error, db) => 
      {
        ...
      });
如果由于transfilation设置或lib不支持lambda而必须保留函数,请将作用域保存在变量中,如:

var self = this;
var DBConnection = MongoClient.connect(connectionString, function(error, db)  
      {
        ... self.dbConnection = db;
      });

connectconnectionString,错误,db=>{…}MDN中有关ES6 Arrow函数的更多信息可能重复: