exports 和 module.exports 用法上的區別

首先要知道,exports 和 module.exports 是 node 支持的導出方式,那麼這兩個導出命令在用法上有啥區別呢?

這裏直接通過兩個簡單的例子進行說明:

// hello1.js
// exports方式導出模塊
exports.hello = function () {
  console.log('Hello World!');
};
// hello2.js
// module.exports 方式導出模塊
module.exports = function () {
	console.log('Hello World');
}

使用require的方式分別引入上面兩個模塊:

// test.js
var hello1 = require('./hello1.js');
var hello2 = require('./hello2.js');

// 調用函數
hello1.hello(); 	// Hello World
hello2();			// Hello World

總結

exports 對象是當前模塊的導出對象,用於導出模塊公有方法和屬性。別的模塊通過 require函數使用當前模塊時得到的就是當前模塊的exports對象。

module 對象可以訪問到當前模塊的一些相關信息,模塊導出對象默認是一個普通對象。

上面的話總結起來就是三點:

  • module.exports 初始值爲一個空對象 {}
  • exports 是指向的 module.exports 的引用
  • require() 返回的是 module.exports 而不是 exports
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章