如何从子节点模块(或扩展节点模块)的对象访问父节点模块的功能?

问题描述 投票:0回答:1

假设有一个现有的节点模块ParentModule,我通过扩展ParentModule创建一个ChildModule。我向 ChildModule 添加了更多函数和属性。

实现过程中,如何从ChildModule的对象中访问ParentModule的功能

ParentModule.js - 父属性-1 - 父属性-2 。 。 。 - 父函数-1 - 父函数-2 - 父函数-3 。 。 。 导出=父模块

ChildModule.js 导入父模块

- childProperty-A
- childProperty-B
.
- childFunction A
.
Exports = ChildModule

在实现过程中,我想使用 as var cModule = require("ChildModule");

那么我怎样才能像这样访问=> cModule.parentFunction-1()?

或者

如何实现这个cModule.parentFunction-1()?

请告诉我是否有解决办法?

请注意:上面我没有写任何语法,只是为了解释。

node.js node-modules
1个回答
0
投票

执行此操作的典型方法是让您的子模块导出一个函数,该函数接受一个函数作为参数,然后您可以调用该函数。因此,作为示例,让我们制作

parentModule.js
:

function parentFunction() {
  console.log("This is the parent function!");
}

const cModule = require("cModule.js")(parentFunction);

childModule.js


function childFunction(parentFunction) {
  console.log("This is the child function. I twill call the parent's function.");
  parentFunction();
}

module.exports = function(parentFunction) {
  return {
    childProperty1: childProperty1,
    childProperty2: childProperty2,
    childFunctionThatWantsTheParentFunction: () => childFunction(parentFunction)
  }
}

这类似于我喜欢填充 Express 路线并将它们分离到自己的文件中的方式 - 我有导出单个函数的路线文件,并且该函数采用

app
创建的
Express()
函数。示例:

module.exports = function(app) {
  app.get("/", function(req, res) {
    res.send("Hello!");
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.