【问题标题】:Updating an object attribute from a method从方法更新对象属性
【发布时间】:2019-03-08 01:08:03
【问题描述】:

我试图了解为什么以下代码不起作用。基本上,我想在 Node 模块中处理数据库连接,同时使用相同的数据库连接。

这是我的模块:

var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";

module.exports = {
  resource: null,
  connect: function() {
    MongoClient.connect(
        url,
        function(err, db) {
            if (err) throw err;
            console.log("Connected!");
            this.resource = db; // Updating the object's attribute
        }
    );
  },
};

还有我的主文件:

var db = require('./db.js');
db.connect(); // Outputs "connected!"

http.createServer(function (req, res) {
  console.log(db.resource) // Outputs "null"
}).listen(8080);

resource 属性永远不会更新。我怀疑是范围问题,但我不知道如何解决。

【问题讨论】:

    标签: javascript node.js scope node-modules


    【解决方案1】:

    使用function() 来定义exports.connect 和对MongoClient.connect 的回调会导致函数体上的this(“上下文”)绑定更改为函数本身。要避免这种行为,请使用 ES6 的箭头函数语法,它不会更改上下文绑定:

    var MongoClient = require("mongodb").MongoClient;
    var url = "mongodb://localhost:27017";
    
    module.exports = {
      resource: null,
      connect: () => {
        MongoClient.connect(
            url,
            (err, db) => {
                if (err) throw err;
                console.log("Connected!");
                this.resource = db; // Updating the object's attribute
            }
        );
      },
    };
    

    或者您可以将connect 定义移到对象之外,并通过使用完整的对象路径来分配exports.resource,如下所示:

    var MongoClient = require("mongodb").MongoClient;
    var url = "mongodb://localhost:27017";
    
    module.exports = {
      resource: null,
      connect: undefined
      },
    };
    
    module.exports.connect = function() {
        MongoClient.connect(
            url,
            function(err, db) {
                if (err) throw err;
                console.log("Connected!");
                module.exports.resource = db; // Updating the object's attribute
            }
        );
    };
    

    【讨论】:

    • 谢谢。实际上只需将“this.resource = db”更改为“module.exports.resource = db”即可解决问题。也就是说,我认为是时候熟悉箭头语法了。
    猜你喜欢
    • 2018-12-19
    • 2021-08-07
    • 2021-08-13
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2012-03-16
    相关资源
    最近更新 更多