在express / node中使用全局变量

时间:2014-03-23 03:01:01

标签: javascript node.js express global-variables scope

试图找到解决方案,我发现了4个解决方案,但我想知道哪个是更好/最佳实践。为什么! :P

1。使用req.app.get()

// app.js

app.set('settings', { domain: 'http://www.example.org' });

// other file

console.log(req.app.get('settings'));

2。使用req.app.settings(类似于上面)

// app.js

app.set('settings', { domain: 'http://www.example.org' });

// other file

console.log(req.app.settings.settings);

第3。导出app对象,这样我就可以访问不带req对象的app.get()

// app.js

app.set('settings', { domain: 'http://www.example.org' });
module.exports = app;

// other file

var app = require('../app');
console.log(app.get('settings'));

4。使用全局变量。可能是坏主意,但......不是"设置"无论如何都是全球化的事情(我可以避免重复使用,因此我不会出现范围问题)

// app.js

settings = { domain: 'http://www.example.org' };

// other file

console.log(settings);

1 个答案:

答案 0 :(得分:1)

简要说明:

<强> 1。使用req.app.get()

在这里,我们为全局属性定义访问器方法(getter / setter)。所以它的语法正确且易于理解。

<强> 2。使用req.app.settings(类似于上面)

在这里,我们定义了setter,但没有使用getter来访问值。 IMO,不是一个好方法。此外,它也很难理解。

console.log(req.app.settings.settings);

第3。导出app对象,这样我就可以访问不带req对象的app.get()

为什么,如果可以访问文件,则需要导入文件。如果您具有app模块的高依赖性(例如,您需要的大量全局设置),这可能很有用,这通常是构建应用程序时的情况。

<强> 4。使用全局变量。可能是坏主意,但......不是&#34;设置&#34;无论如何都是全球化的事情(我可以避免重复使用,因此我不会遇到范围问题) 这不是一个好方法,因为在这种情况下代码是不可维护的。

IMO,优先级如下:1&gt; 3> 2&gt; 4。