最近正在學(xué)習(xí)nodejs,看到nodejs模塊這塊,發(fā)現(xiàn)nodejs模塊有兩種方式對外暴露方法
exports和module.exports
可是這兩種使用起來到底有什么區(qū)別呢???
看了很多文章,長篇大論,始終沒有講清楚區(qū)別,自己也是看了很多,終于搞清楚了,給大家分享一下
根據(jù)使用方法來說
通常exports方式使用方法是:
exports.[function name] = [function name]
moudle.exports方式使用方法是:
moudle.exports= [function name]
這樣使用兩者根本區(qū)別是
**exports **返回的是模塊函數(shù)
**module.exports **返回的是模塊對象本身,返回的是一個類
使用上的區(qū)別是
exports的方法可以直接調(diào)用
module.exports需要new對象之后才可以調(diào)用
二話不說,擼代碼!
1. exports方式
先創(chuàng)建一個exports_mode.js
var sayHello = function(){
console.log('hello')
}
exports.sayHello = sayHello
console.log(exports);
console.log(module.exports);
然后寫一個test.js調(diào)用下試試看
var exports_mode = require('./exports_mode')
exports_mode.sayHello()
輸出:
發(fā)現(xiàn)此時exports和module.exports對象輸出的都是一個sayHello方法,
為什么module.exports也有exports方法了,簡單點理解就是
exports是module.exports的一個引用,exports指向的是module.exports
我們來驗證下,在exports_mode.js最后一行添加一句代碼
var sayHello = function(){
console.log('hello')
}
exports.sayHello = sayHello
console.log(exports);
console.log(module.exports);
console.log(exports === module.exports);
發(fā)現(xiàn)console.log(exports === module.exports)返回的是true,
說明exports和module.exports是同一個對象
下來看看
2. module.exports方式
首先創(chuàng)建module_exports_mode.js
var sayHello = function(){
console.log('hello')
}
module.exports = sayHello
console.log(module.exports);
console.log(exports);
console.log(exports === module.exports);
然后測試一下
var module_export_mode = require('./module_exports_mode')
module_export_mode.sayHello()
發(fā)現(xiàn)輸出報錯了!
為什么呢,因為我們的調(diào)用方式錯了,一開始就說到了
**module.exports **返回的是模塊對象本身
正確的調(diào)用
var module_export_mode = require('./module_exports_mode')
new module_export_mode()
同時我們可以看到,輸出的module.exports對象內(nèi)容就是一個[Function],在javascript里面是一個類
使用這樣的好處是exports只能對外暴露單個函數(shù),但是module.exports卻能暴露一個類
我們把module_exports_mode.js擴展一下
var xiaoming = function(name){
this.name = name
this.sayHello = function(){
return 'hello '+this.name
}
this.sayGoodBye = function(){
return 'goodbye '+this.name
}
}
module.exports = xiaoming
console.log(module.exports);
console.log(exports);
console.log(exports === module.exports);
然后測試
var xiaoming = require('./module_exports_mode')
var xiaoming = new xiaoming('Lucien')
console.log(xiaoming.sayHello())
console.log(xiaoming.sayGoodBye())
使用方法和javascript的類創(chuàng)建對象一毛一樣
exports.[function name] = [function name]
moudle.exports= [function name]
以上就是這兩種方式的使用區(qū)別。
等等,還沒完。。。
上面有提到
exports是module.exports的一個引用,exports指向的是module.exports
也就是說exports的方法module.exports也是一定能完成的
exports.[function name] = [function name]
moudle.exports= [function name]
所以,在使用上
** moudle.exports.[function name] = [function name] **
** 是完全和 **
** exports.[function name] = [function name] **
** 相等的 **
但是我們通常還是推薦使用exports.[function name],各司其職,代碼邏輯清晰