最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何导入导出模块将值返回到其他js文件

运维笔记admin17浏览0评论

如何导入导出模块将值返回到其他js文件

如何导入导出模块将值返回到其他js文件

试图掌握导出导入/导出过程并将函数和它们返回到另一个文件。我遇到了这个很好的例子!但无法将其转移到另一个文件中..

例如,运行node testing.js时出现此错误。我认为你可以通过你的参数。

错误输出

console.log(testClass.authy)(app);
                             ^

ReferenceError: app is not defined

helper.js

module.exports.auth = function (app) {
    console.log("return authy")
    var app = "1";
    return app;
};

testing.js

const testClass = require('../commands/helper.js');
console.log(testClass.auth)(app);
回答如下:

首先,在将函数的结果记录到控制台时,您应该使用console.log(function()),而不是console.log(function)()

其次,你将'app'作为参数传递,这是你赋予函数的值,然后立即重新定义它。你的函数不需要任何参数,它应该只是function() { ... },然后被称为testClass.auth()。现在,您正在尝试将变量'app'传递给您尚未定义的函数。

所以最后,你的代码应该是:

helper.js

module.exports.auth = function () {
  console.log("return authy")
  var app = "1";
  return app;
};

testing.js

const testClass = require('../commands/helper.js');
console.log(testClass.auth());

'app'的值返回到console.log函数,然后显示它。希望这可以帮助!

发布评论

评论列表(0)

  1. 暂无评论