【发布时间】:2018-05-06 11:03:54
【问题描述】:
一般的想法是我需要一个 module.export 函数中的函数。假设我有两个文件:foo.js 和 math.js。它们在同一个文件夹中。
// foo.js
var calc = require('./math.js');
var a = 3, b = 5;
console.log(calc.calc(a, b));
它将请求一个导出模块将两个数字相加。
// math.js
module.exports = {
calc: function(a, b) {
// I need to call another function which does the math right here.
}
}
如果我像下面尝试的那样嵌套它们,它只会返回undefined。
// math.js
module.exports = {
calc: function(a, b) {
x(a, b);
function x(a, b) {
return a + b;
}
}
}
返回undefined。
// math.js
module.exports = {
calc: function(a, b) {
x(a, b);
}
}
function x(a, b) {
return a + b;
}
返回b is not a function。
如何在导出模块中嵌套函数?我是 Node 新手,所以这听起来像是一个基本的问题,但我真的无法让它发挥作用。
编辑:这是非常简化的。我知道我可以在第一个 calc 函数中进行数学运算,但这在我的实际代码中是不可能的。
【问题讨论】:
-
你没有从
calc返回任何东西,因为你错过了x(a, b);调用前面的return。 -
b is not a function错误与您显示的代码不匹配。
标签: javascript node.js module require