Node.js:模块系统,对象引用

时间:2013-10-23 18:46:57

标签: node.js

// connections.js
...
module.exports = {
    conn: {
        mongodb: {
            connect: function() {throw ...},
            disconnect: function() {throw ...},
            getState: function() {throw...}
        },
        mysql: {
            connect: function() {throw ...},
            disconnect: function() {throw ...},
            getState: function() {throw ...}
        }
    },
    drivers: {
        mongoose: mongoose,
        mysql: mysql
    },
    states: connectionStates,

    setup: function(config, cb) {
        // provides concrete implementations of connect(), discconnect(),
        // getState(), sets up listeners to relay connection events 
        this.conn.mongodb = setupMongo(config.mongodb); 
        this.conn.mysql = setupSql(config.mysql);
        ...
        cb();
    }
};

现在,如果我将其包含在:

// main.js

var connections = require(__dirname + '/connections'),   
    conn = connections.conn,
    db = conn.mongodb;

// connectionections.setup() not been called yet
exports.foo = function() {
    // connections.setup() already been called before this point
    db.connect(...);            // fails - error thrown - using the abstract function
    conn.mongodb.connect(...);  // works
}

为什么第一个失败? db var应该包含对connections.conn.mongodb的引用?至少,我希望无论是工作还是不工作。允许第一个失败和第二个失败的区别是什么?谢谢

1 个答案:

答案 0 :(得分:1)

它在第一种情况下失败,因为setup()在不同的作用域中被调用而db / conn.mongodb在调用setup时发生了分歧(写入时有一个副本)。如果在exports.foo函数中比较db和conn.mongodb,您应该看到conn.mongodb已使用setupMongo初始化,而db仍然具有未初始化的版本。不确定调用connections.setup的代码是什么样的,但从外观上看,db!=== conn.mongodb。