gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:57:59 25 4
gpt4 key购买 nike

我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com