如何将变量传递到NodeJS模块? [英] How to pass variables into NodeJS modules?

查看:287
本文介绍了如何将变量传递到NodeJS模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个JS文件中包含另一个。我怎么能在包含的模块中设置变量?



我认为做这样的事情可以工作

  var mymodule = require('mymodule.js'); 
mymodule.myvariable ='test';

然后在mymodule中

  this.myvariable ==='test'; 

但这不起作用,它是 undefined 。将值传递给模块的各种选项有哪些?我可以将变量作为参数添加到myModule中调用的每个函数中,但这并不理想。



有没有一种方法可以不使用全局变量,所以我可以在各种必需的模块中独立设置变量,像这样?

  var mymodule1 = require('mymodule.js') ; 
var mymodule2 = require('mymodule.js');
mymodule1.myvariable ='test1';
mymodule2.myvariable ='test2';


解决方案

NodeJS require / code>将永远加载模块一次,因此您需要在您的模块中实施范围界定,其中模块的不同实例可以存在自己的内部状态。



你可以将你的模块实现为一个JS类,例如:

  var MyModule = function(){}; 

MyModule.prototype.someFunction = function(params){
this.someVar = params;
}

MyModule.prototype.anotherFunction = function(key,value){
this [key] = value;
}

module.exports = MyModule;

然后在您的代码中;

  var MyModule = require('MyModule'); 

someModule = new MyModule();

//使用它的getters / setters / functions对待someModule类似对象


In one of my JS files I include another one. How can I set variables in the included module?

I thought doing something like this would work

var mymodule = require('mymodule.js');
mymodule.myvariable = 'test';

And then in mymodule

this.myvariable === 'test';

But this doesn't work, it's undefined. What are the various options for passing a value into a module? I could just add the variable as a parameter to every function I call in mymodule, but that isn't ideal.

Is there a way to do it without globals, so that I can set the variables independently in various required modules, like this?

var mymodule1 = require('mymodule.js');
var mymodule2 = require('mymodule.js');
mymodule1.myvariable = 'test1';
mymodule2.myvariable = 'test2';

解决方案

NodeJS require() will always load the module once so you will need to implement scoping into your module where different instances of the module can exist with their own internal state.

You can implement your module as a JS class like:

var MyModule = function(){};

MyModule.prototype.someFunction = function(params){
    this.someVar = params;
}

MyModule.prototype.anotherFunction = function(key, value){
    this[key] = value;
}

module.exports = MyModule;

Then in your code;

var MyModule = require('MyModule');

someModule = new MyModule();

// treat someModule like an object with its getters/setters/functions

这篇关于如何将变量传递到NodeJS模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆