我是看七天學會NodeJS 入的坑. 結果被一同事給問住了. exports和module.exports有啥區別.做爲一新手.根本沒搞清楚. 一翻測試獲得了以下的結論javascript
exports = module.exports
不過別急.裏面有好多有意思的東西java
首先.nodejs啓動後,會爲每一個加載的js文件會產生一個module對象(此處待驗證由於沒仔細找相關文檔,只是目測結果)node
app.js文件代碼:git
console.log(module)
輸出:github
{ id: '.', exports: {}, parent: null, filename: 'E:\\node\\test\\app.js', loaded: false, children: [], paths: [ 'E:\\node\\test\\node_modules', 'E:\\node\\node_modules', 'E:\\node\\node\\node_modules', 'E:\\node\\node_modules', 'E:\\node_modules' ] }
這是app.js文件輸出的module對象, 相信對你們.應該都能猜到裏面各個參數的意思.但對新手來講. exports 確是個深深的坑.
咱們來修改下app.jsapp
var foo = require("./foo");
新建foo.js測試
module.exports.hello = 'bbb' console.log(exports.hello) exports.hello = 'aaa' console.log(module.exports.hello)
輸出:ui
bbb aaa
哎喲 咱們操做是同個東西嗎. 沒錯.這就是開篇的那個結論. 但接下來. 有意思的東西. 繼續改
app.jsprototype
var foo = require("./foo"); console.log(foo);
foo.jscode
var View = function (){} View.prototype.test = function(){ console.log('test') } View.test1 = function(){ console.log('test1') } exports = View;
我預期它會給我輸出View這個function對象 (由於我javascript很矬因此預期錯了.) 結果返回了 {}
怎麼了?沒怎麼.理解完全錯了唄. 繼續改:
app.js
.... console.log(foo.view);
foo.js
.... exports.view = View;
終於正常輸出了. 好像明白什麼了. require 真正返回的是module的exports屬性. 而 單純foo.js中的exports 只不過是module的exports屬性的引用 . 直接對exports賦值.對module是沒有任何改變的.固然不會正常輸出. 這就完了嗎? 沒有. 下面算是語法分析了. foo.js再改 我要給我導出的對象用exports加點屬性
.... // exports.view = View; module.exports = View; exports = function (argument) { // body... }
結果. 它還真xxx了. 個人xxx屬性呢.
{ [Function] test1: [Function] }
唉.此次真的是硬傷問題了. module.exports = View 這不是也改了 module的exports 而 exports仍是指向原來的那個{}
因此foo.js的正確姿式
.... exports = module.exports = View; exports.xxx= function (argument) { // body... }