【问题标题】:Node.js How to import and export modules with sub functionsNode.js 如何使用子功能导入和导出模块
【发布时间】:2017-07-10 06:16:33
【问题描述】:

我正在编写一个应用程序并遇到了一些麻烦。我在 JavaScript 中设置了一个“类”,并在该类中调用了多个 this.demo = function(){}。当我导出模块然后在另一个页面上导入,然后尝试使用其中一个子功能时,我的应用程序告诉我它无法识别该功能。这是一个例子..我应该怎么做?

function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.demo = demo;

然后在另一个类中导入 demo.js 文件

function newClass(){
   this.demo = require('./demo');
   this.demo.test('Hello');
}

编辑告诉我它无法识别测试...

【问题讨论】:

  • require('./demo')demo.js 返回module.exports 对象。你给了它一个属性,叫做demo,它是一个构造函数。

标签: node.js node-modules


【解决方案1】:

您的代码中存在导出错误。

function demo(){ this.test = function(msg){console.log(msg);} }
module.exports.test = demo;

现在你可以正确调用它了:

function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

   // If you're still confused, use the console.log!
   console.log(this.demo);

}

console.log(this.demo) 的输出将显示结构或您的演示文件。


编辑:要获取require 调用的结果,请像这样导出:

module.exports = function demo(){ this.test = function(msg){console.log(msg);} }

现在你直接调用:

function newClass(){

   this.demo = require('./demo');
   this.demo.test('Hello');

}

【讨论】:

  • 感谢您的快速回复。重新表述我的问题,我可以调用 this.demo.test 还是只能调用 this.demo?
  • 我已经用一个示例更新了答案,其中函数本身被导出为模块的根目录。希望它能解决您的问题。
  • 您发布的内容将字符串发送到函数演示,但没有输出,因为它永远不会到达 this.test 函数。从你注意到的.. 我不能使用与我正在导出的函数相同的导出名称。您未能解释的是,一旦我导出正确,我就可以使用 this.demo.test("Hello") 调用子函数。
猜你喜欢
  • 2021-08-21
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-12-06
相关资源
最近更新 更多