Node.js 如何导入导出带有子功能的模块

Node.js How to import and export modules with sub functions

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

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

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

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

小编告诉我不识别test...

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

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');

}