【问题标题】:Node JS function undefined after execution执行后节点JS函数未定义
【发布时间】:2017-10-15 17:29:04
【问题描述】:

我正在尝试在节点 JS 中导入简单类,函数执行后我得到 undefined。为什么我得到 undefined

index.js

const ctrl = require('./math');

console.log(ctrl.addFunction());
console.log(ctrl.sunFunction());

ma​​th.js

module.exports = {
  addFunction: function() {
    console.log('printing addFunction');
  },
  sunFunction: function() {
    console.log('printing sunFunction');
  }
};

输出: 节点 index.js

打印 addFunction
未定义
打印太阳功能
未定义

【问题讨论】:

  • undefined 是两个函数的返回值,由您的index.js 打印。
  • 为什么是两个console.log?只需调用没有console.logctrl.addFunction(); 的函数
  • 如果我的函数没有返回任何值,那么它的 undefined 得到了它。谢谢@Sirko

标签: node.js node-modules


【解决方案1】:

因为您尝试打印函数返回的任何内容,而它们不返回任何内容,它们只打印来自console.log 的字符串。

执行轨迹是:

console.log(ctrl.addFunction());
     > addFunction() 
             > prints 'printing addFunction' //First console.log in output
             > returns nothing
     > console.log(undefined) //Second console.log in output

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 2018-03-01
    • 2023-03-23
    相关资源
    最近更新 更多