2014-11-21 102 views
2

调用父模块内部的功能让我们说我有一个名为parent.js用下面的源代码文件:的NodeJS - 从孩子模块

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() 

,但它不工作。奇怪的是,当我执行console.log(module.parent.exports)child.js,以下输出出现:

{ f: [Function] } 

那么我为什么不能直接调用f()

回答

0

作为替代到什么利詹金斯建议,你可以改变你代码到这里(很难解释而不显示代码)

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(); 
     } 
    }; 
} 
2

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

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

module.exports = child; 

然后在parent.js调用目标是这样的:

child.target(parent.f);