0

我正在使用一个函数练习一些模块导出练习,该函数在模块导出中传递了一个返回语句,然后导入到一个新文件中,它告诉我total没有定义?为什么会这样?

代码:

文件 1:

// Using Async & Await with MODULE EXPORT.

const googleDat = require('../store/google-sheets-api.js');

//passing a let var from a function to another file
let total = googleDat.addVat(100);
console.log(total);

文件 2:

function addVat(price) {
  let total = price*1.2
  return total
};

module.exports = {
  total
};

结果:

在此处输入图像描述

4

2 回答 2

1

那是因为您导出了一个尚未初始化的变量并且您没有导出您的函数:


function addVat(price) {
  //defining variable with let work only in this scope
  let total = price*1.2
  return total
};

//In this scope, total doesn't exists, but addVat does.

module.exports = {
  total //So this is undefined and will throw an error.
};

你想要做的是导出你的函数,而不是里面的结果。


function addVat(price) {
  return  price * 1.2;
};

module.exports = {
  addVat
};

于 2021-09-13T05:50:13.707 回答
0

在文件 2 上,您应该导出 addVat() 函数本身,而不仅仅是它的返回值。试试这个:

exports.addVat = (price) => {
  let total = price*1.2
  return total
};

于 2021-09-13T05:54:38.450 回答