在express/node中使用全局变量

Fél*_*anz 6 javascript scope global-variables node.js express

尝试寻找解决方案时,我找到了 4 个解决方案,但我想知道哪一个更好/最佳实践。为什么!:P

1.使用req.app.get()

// app.js

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

// other file

console.log(req.app.get('settings'));
Run Code Online (Sandbox Code Playgroud)

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

// app.js

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

// other file

console.log(req.app.settings.settings);
Run Code Online (Sandbox Code Playgroud)

3.导出app对象,这样我就可以访问app.get()而无需req对象

// app.js

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

// other file

var app = require('../app');
console.log(app.get('settings'));
Run Code Online (Sandbox Code Playgroud)

4. 使用全局变量。可能是个坏主意,但是……“设置”不是一个全局的东西吗?(我可以避免重复使用它,这样就不会出现范围问题)

// app.js

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

// other file

console.log(settings);
Run Code Online (Sandbox Code Playgroud)

Moh*_*dey 2

简要意见:

1.使用req.app.get()

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

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

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

console.log(req.app.settings.settings);
Run Code Online (Sandbox Code Playgroud)

3.导出app对象,这样我就可以访问app.get()而无需req对象

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

4. 使用全局变量。可能是个坏主意,但是……“设置”不是一个全局的东西吗?(我可以避免重用它,这样我就不会遇到范围问题)这 不是一个好方法,因为在这种情况下代码不可维护。

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