简体   繁体   English

使用 require 在另一个文件中访问 Node.js 中立即调用的函数表达式变量

[英]Accessing an Immediately Invoked Function Expression variable in Node.js in another file using require

File 1 - Monitor.js文件 1 - Monitor.js

var MONITOR = (function () {

// File Content

return {
  doThing: function() {
    doThing();
  }
};
})();

File 2 - Test.js文件 2 - Test.js

var monitor = require('../public/js/monitor.js');

I want to access doThing() in File 2. I have tried various syntax and no luck so far.我想访问文件 2 中的doThing() 。到目前为止,我尝试了各种语法,但都没有成功。

From the frontend HTML I can simply include Monitor.js in a script tag, and call MONITOR.doThing();在前端 HTML 中,我可以简单地将 Monitor.js 包含在脚本标记中,然后调用MONITOR.doThing(); without trouble but in Test.js this is proving difficult.没有问题,但在 Test.js 中这被证明是困难的。

Any advice on how?有关如何操作的任何建议?

You have to export MONITOR so that someone else can access it with require() .您必须导出 MONITOR 以便其他人可以使用require()访问它。

Add this:添加这个:

module.exports = MONITOR;

at the bottom of Monitor.js.在 Monitor.js 的底部。


And, if you want the monitor.doThing() method to return some value, then you have to add a return statement to the function as in:而且,如果您希望monitor.doThing()方法返回一些值,那么您必须向函数添加一个return语句,如下所示:

var MONITOR = (function () {

// File Content

return {
  doThing: function() {
    return "hello";
  }
};
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM