【问题标题】:NodeJS multiple functions within a module export一个模块导出中的 NodeJS 多个功能
【发布时间】:2018-05-06 11:03:54
【问题描述】:

一般的想法是我需要一个 module.export 函数中的函数。假设我有两个文件:foo.jsmath.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


【解决方案1】:

return 语句结束函数执行并指定要返回给函数调用者的值

在嵌套函数中

module.exports = {
    calc: function(a, b) {
        return  x(a, b);    //Function should Return a Value    
        function x(a, b) {
       return a + b;    
        }
    }
}

在私有作用域方法中

module.exports = {
    calc: function(a, b) {
        return  x(a, b);                
    }
}

function x(a, b) {
       return a + b;    
        }

输出

-->foo.js

var calc = require('./math.js');
console.log(calc.calc(1,2)); ----> 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2017-05-04
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多