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

假设我有一个名为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()呢?

作为Lee Jenkinsbuild议的替代scheme,您可以将您的代码更改为(不需要显示代码就难以解释)

parent.js

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

child.js

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

你可能会考虑使用callback函数:

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

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

 child.target( parent.f );