gpt4 book ai didi

javascript - node.js:从其他文件访问导出的函数

转载 作者:行者123 更新时间:2023-11-30 16:28:45 24 4
gpt4 key购买 nike

我有以下代码:

// jira.js
var exports = module.exports = {};

module.exports = function () {
var exported = {};
..
exported.myMethod= function (bugId, done) {
..
}
..
return exported;
};

我想使用同一目录中其他文件 bugs.js 中的 myMthod 函数:

var exports     = module.exports = {};
var jira = require('./jira');

module.exports = function () {
var exported = {};
..
exported.secondMethod= function (bugId, done) {
jira.myMethod(...) {
}
..
}
..
return exported;
};

当我尝试从 bugs.js 访问 myMthod 时,我得到“undefined”。在调用 jira.myMthod() 上方执行 console.log(jira) jyst 后,我​​看到整个 js 文件已注销。

我如何让它工作?

请指教,

谢谢!

最佳答案

因为 jira 中的 module.exports 是一个函数,所以您需要执行它以获得返回值(您可以像这样要求它:var jira = require('./jira' )(); 将返回导出的函数)。

但在我看来,这是多余的。我更喜欢这种语法:

// jira.js

function myMethod (bugId, done) {
..
}
..
return {
myMethod : myMethod
};

当你需要 jira 时,它会运行代码(在本例中,定义函数)并返回它

关于javascript - node.js:从其他文件访问导出的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681689/

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