2014-11-21 107 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);