简体   繁体   English

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

[英]Node.js: module system, object references

// 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();
    }
};

Now if I include this as: 现在,如果我将其包括为:

// 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
}

Why does the first one fail? 为什么第一个失败? The db var should contain a reference to connections.conn.mongodb ? db var应该包含对connections.conn.mongodb的引用? At very least, I'd expect both to either work, or not work. 至少,我希望两者都可以起作用,也可以不起作用。 What is the difference that allows the first to fail and second to succeed? 允许第一个失败和第二个成功的区别是什么? Thank you 谢谢

Its failing in the first case because setup() was called in a different scope and db/conn.mongodb diverged (with a copy on write) when setup was called. 在第一种情况下,它的失败是因为在调用setup时,setup()在不同的范围内被调用,并且db / conn.mongodb发生了分歧(写时带有副本)。 If you compare db and conn.mongodb in the exports.foo function, you should see that conn.mongodb has been initialized with the setupMongo and db still has the uninitialized versions. 如果在exports.foo函数中比较db和conn.mongodb,则应该看到conn.mongodb已使用setupMongo初始化,而db仍具有未初始化的版本。 Not sure what the code looks like that is calling connections.setup, but from the looks of this, db !=== conn.mongodb. 不确定代码看起来像是调用connections.setup,但是从外观上看,db!=== conn.mongodb。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM