NodeJS / ES6:无法设置未定义

时间:2018-01-29 19:57:08

标签: 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 + ':' + 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在到达this.dbConnection = db;时崩溃,说明TypeError: Cannot set property 'dbConnection' of undefined

我很确定它与在回调中使用有关,这会搞砸范围。我怎么能绕过这个呢?回调范围内的任何操作都不会被隔离且无法引用this吗?

另外,作为一个附带问题,这是一个错误的代码实践初始化null属性,就像我在构造函数中做的那样?如果是这样,那么更合适的做法是什么?

1 个答案:

答案 0 :(得分:1)

的确如果你想保持你的范围使用lambda而不是:

var DBConnection = MongoClient.connect(connectionString, (error, db) => 
      {
        ...
      });

如果由于您的转换设置而必须保留您的功能,或者lib不支持lambda,请将范围保存在如下变量中:

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