Node.js:需要本地人
我想要的是
是否有可能将本地人传递到所需的模块? 例如:
// in main.js var words = { a: 'hello', b:'world'}; require('module.js', words); // in module.js console.log(words.a + ' ' + words.b) // --> Hello World
我这样问是因为在PHP中当你需要或者包含的时候,包含其他文件的文件会inheritance它的variables,这在某些情况下非常有用,如果在node.js中也可以这样做,我会很高兴。
我已经尝试过,没有工作
var words = { a: 'hello', b:'world'}; require('module.js', words);
var words = { a: 'hello', b:'world'}; require('module.js');
这两个都给ReferenceError: words is not defined
在module.js
调用ReferenceError: words is not defined
words
那么没有全局variables是可能的吗?
你想要做的是用一个参数导出它,所以你可以把它传递给variables。
module.js
module.exports = function(words){ console.log(words.a + ' ' + words.b); };
main.js
var words = { a: 'hello', b:'world'}; // Pass the words object to module require('module')(words);
您也可以砍掉.js中的要求:)
问题是:你想达到什么目的?
如果你想导出一个静态函数,你可以使用tehlulz的答案 。 如果你想在exports属性中存储一个对象,并从require-caching节点中获益,那么提供一个(肮脏的)方法就是给你全局variables。 我想这是你所尝试的。
在Web浏览器上下文中使用JavaScript,您可以使用window
对象来存储全局值。 节点只提供一个对所有模块全局的对象: process
对象:
main.js
process.mysettings = { a : 5, b : 6}; var mod = require(mymod);
mymod.js
module.exports = { a : process.mysettings.a, b : process.mysettings.b, c : 7};
另外,如果你对输出caching不感兴趣,你可以这样做:
main.js
var obj = require(mymod)(5,6);
mymod.js
module.exports = function(a,b){ return { a : a, b : b, c : 7, d : function(){return "whatever";}}; };