2016-07-28 126 views

回答

1

exports是對應於module.exports之前的任何對象。我認爲這是由於一些遺留代碼造成的,但基本上人們使用module.exports如果他們想用自己的對象或函數替換整個對象,而如果他們只想從模塊中掛起函數,則使用exports。這是一個有點混亂在第一,但本質上exports.install只是意味着調用代碼會做這樣的事情:

const mod = require('that-module'); 
mod.install(params, callback); // call that function 

你看這個框架可能是使用它作爲一個引導過程的一部分,據我所知它不對節點引擎本身具有重要意義。

0

是的,這是一回事。您可以使用2種方式之一來設置您的代碼。

不同的是memory。他們指向相同的記憶。你可以認爲exports像一個變量,你不能用這種方式來導出模塊:

鑑於此模塊:

// test.js 
exports = { 
    // you can not use this way to export module. 
    // because at this time, `exports` points to another memory region 
    // and it did not lie on same memory with `module.exports` 
    sayHello: function() { 
     console.log("Hello !"); 
    } 
} 

下面的代碼將得到錯誤:TypeError: test.sayHello is not a function

// app.js 
var test = require("./test"); 
test.sayHello(); 
// You will get TypeError: test.sayHello is not a function 

您必須使用module.exports導出模塊的正確方法:

// test.js 
module.exports = { 
    // you can not use this way to export module. 
    sayHello: function() { 
     console.log("Hello !"); 
    } 
} 

// app.js 
var test = require("./test"); 
test.sayHello(); 
// Console prints: Hello ! 

所以,它只是開發者的風格。