javascript - 将参数传递给被调用的模块

标签 javascript node.js

我的 app.js 包含:

var m1 = require("./m1");
m1.f1(...);

我的 m1.js 包含:

var m1 = module.exports = {};
m1.f1 = function(...) { };

我想在从 app.js 加载 m1 时传递 somevariable:

var m1 = require("./m1")(somevariable);

如何编写 m1.js 以便 m1.f1 的函数定义可以访问 somevariable

最佳答案

如果你希望能够做到这一点:

var m1 = require("./m1")(somevariable);            // it is equivalent to var m = require("./m1"); and then m(someVariable); so m (the exports of the module m1.js) should be a function

那么 m1.js 中的 module.exports 应该是一个函数:

// m1.js:
module.exports = function(theVariable) {
    // use variable then return the following object:

    return {
        f1: function() { /* ... */ }
    };
}

现在您可以像这样在 app.js 中使用该模块:

// app.js:
var m1 = require("./m1")(someVariable);

m1.f1(/* ... */);

module.exports 是加载模块时调用 require 返回的值。

关于javascript - 将参数传递给被调用的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47459488/

相关文章:

javascript - 在node.js中的elasticsearch中创建空索引

javascript - onClick 优先于 javascript 中的 addEventListener?

javascript - 我无法使用 Node.js 连接到我的 mysql 数据库(connection.connect 问题)

mysql - 使用 Node 将字典数组插入MySQL数据库

javascript - 为什么 'this' 在箭头函数中引用时返回 'undefined' 而在匿名函数中调用时却不返回?

javascript - Ember 中的 CSS 类是否需要多个计算属性?

php - HTML 表单 -> Flash 提交按钮 -> 在 Flash 按钮中设置 PHP 变量 -> 提交表单

Javascript 文件未在 express/node.js 中加载

javascript - 将自定义属性添加到 Express 应用程序和请求。最好的方法是什么?

javascript - 使用 Node.js 迁移到 s3 存储