nodejs - 从子模块调用父模块内的函数

nodejs - Call a function inside a parent module from a child module

本文关键字:模块 函数 调用 nodejs      更新时间:2023-09-26

假设我有一个名为parent.js的文件,其中包含以下源代码:

var child = require('./child')
var parent = {
    f: function() {
        console.log('This is f() in parent.');
    }
};
module.exports = parent;
child.target();

以及一个名为 child.js 的文件,其中包含以下源代码:

var child = {
    target: function() {
        // The problem is here..
    }
}
module.exports = child;

我使用以下命令执行该文件:

node parent.js

问题是,我想直接在child.js内部执行f(),而无需使用任何require(...)语句。以前,我尝试在child.js target()内执行此语句:

module.parent.f()

module.parent.exports.f()

但它不起作用。奇怪的是,当我在child.js内部执行console.log(module.parent.exports)时,会出现以下输出:

{ f: [Function] }

那为什么我不能直接打电话给f()呢?

您可以考虑使用回调函数:

var child = {
    target: function( callback ) {
        callback();
    }
}
module.exports = child;

然后在 parent 中.js像这样调用目标:

child.target( parent.f );

您也可以尝试以下设置,使用 require.main(不推荐使用 module.parent) 访问父函数。

父.js

var parent = {} 
parent.f = function(){
      console.log('called parent function from child');
    }
module.exports = {
  parent:parent
}
var child = require('./child.js');

孩子.js

var child = {};
var parent = require.main.exports.parent;
child.f = function(){
  parent.f();
}
//call parent function here
child.f();
module.exports = {
  child:child
}

作为 Lee Jenkins 建议的替代方案,您可以将代码更改为此代码(如果不显示代码,则很难解释)

父.js

var parent = {
    f: function() {
        console.log('This is f() in parent.');
    }
};
var child = require('./child')(parent);
module.exports = parent;
child.target();

孩子.js

module.exports = function (parent) {
    return child = {
        target: function() {
            parent.f();
        }
    };
}