【问题标题】:NodeJS/ES6: Cannot set property of undefinedNodeJS/ES6:无法设置未定义的属性
【发布时间】:2018-07-08 14:34:21
【问题描述】:

我使用 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 属性是一种糟糕的代码做法吗?如果是这样,更合适的方法是什么?

【问题讨论】:

标签: javascript node.js mongodb scope


【解决方案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;
      });

【讨论】:

猜你喜欢
  • 2019-02-09
  • 1970-01-01
  • 2019-06-23
  • 2021-11-27
  • 2022-10-30
  • 2023-02-10
  • 2015-12-07
  • 2013-05-28
相关资源
最近更新 更多