JS – 从一个函数传递连接(对象)到另一个

我是JS的新手,我有一个简单的问题。 我正在编写一个node_redis代码来连接到数据库。 我创build了一个db模块,其中有一个init函数来启动连接。 该模块还具有查询数据库的另一个function。 对于查询,我将需要第一个函数的连接(dbConnection)对象,然后在第二个函数中使用它。 我该怎么做呢? 我可以通过使用全局variables来完成,但大多数地方告诉我它是一个坏主意。

对不起,如果问题是愚蠢的,我正在学习如何编码。 结果谷歌告诉我,它可以通过将其作为对象属性传递来完成。 但是我不知道在我的背景下做事是否是正确的方法,甚至不知道如何去做。

var redis = require('redis'); module.exports = redisDb = { // Initialize the module. Invokes callback when ready (or on error) init: function(config, callback) { // Open the database connection var dbConnection = redis.createClient(config.db.port, config.db.host, {no_ready_check: true}); dbConnection.auth(config.db.authKey, function() { console.log("Connected!"); console.log(dbConnection.keys('*')); }); dbConnection.on('connect' , log('connect')); dbConnection.on('ready' , log('ready')); dbConnection.on('reconnecting', log('reconnecting')); dbConnection.on('error' , log('error')); dbConnection.on('idle' , log('idle...')); dbConnection.on('end' , log('end')); function log(type) { return function() { console.log(type, arguments); } } callback("callback - Connected"); }, getValue: function(key, callback) { dbConnection.hgetall("hosts", function (err, obj) { console.dir(obj); }); } }; 

编辑:尝试另一种方式。 仍然失败。

 module.exports = redisDb = (function() { var config = require('../config'); var redis = require('redis'); return { connection: function(config) { var dbConnection = redis.createClient(config.db.port, config.db.host, {no_ready_check: true}); dbConnection.auth(config.db.authKey, function() { console.log("Authenticated!"); }); return dbConnection }, getValue: function(connection, callback) { connection.hgetall("hosts", function (err, obj) { console.dir(obj); }); } } })(); 

现在有一种方法就像你说的使dbConnection成为一个对象属性一样。 另一种方法是在getValue()调用init() ,这会在每次需要某个值时build立不同的连接。

因为数据库连接是一个有价值的资源,所以我认为最好使用第二个变体。 当然,你需要从init()返回dbConnection

PS:全球variables是最初为这样的事情做的,然后人们看到越less越好。 这就是为什么使用全球variables被认为是不好的风格。

我通过在父函数中声明连接来完成代码的工作。

 module.exports = _redisDb = (function() { var redis = require('redis'); var config = require('../config'); var dbConnection = redis.createClient(config.db.port, config.db.host, {no_ready_check: true}); dbConnection.auth(config.db.authKey, function() { console.log("Authenticated!"); }); var getValue = function() { dbConnection.hgetall("hosts", function (err, obj) { console.dir(obj); }); } return { getValue: getValue } })(); 

虽然上面的工作,我仍然希望有人告诉我如何可以在同一模块的function之间传递variables/对象。