Node中Exports与module.export的使用与区别
最近在看《node開發實戰詳解》時有寫疑問,所以自己就整理了一些資料。下面是node4.*的官方api文檔(http://nodejs.cn/doc/node_4/modules.html#modules_module_exports),我有點看不懂,就拉出node.10*的官方api(https://nodejs.org/dist/v0.10.9/docs/api/modules.html#modules_module_exports)。
?
module.exports與exports的介紹
module.exports與exports都是將函數或者是方法暴露出去,require的時候進行調用,但是2者是有區別的。以下是代碼:
?
//ex.jsexports='danhuangmode';
//mex.js
? module.exports='danhuangmode';
//call_ex_mex.js? var ex=require('./ex');
? var mex=require('./mex');
? console.log(ex);
? console.log('\n');
? console.log(mex);
執行結果:
?
引用exports提供方法,輸出是為一個對象,引用module.exports提供方法,輸出為字符串。
?
exports內部提供接口,在外部引用時之間的關系如何?
exports內部處理暴露方法,是如何處理的,看如下代碼:
var string='this is in exports.js';function ex_fn () {console.log('this in funtion ex_fn'); }var exobj={str1:"str1 exobj",exobjfn: function () {console.log("in function");} };exports.string=string; exports.ex_fn=ex_fn; exports.exobj=exobj; exports=exobj;調用代碼:
var ex=require('./ex');console.log(ex.string); console.log(ex.ex_fn); console.log(ex.exobj); console.log(ex);結果顯示:
?
exports提供的所有接口,直接調用導出實例化的接口對象,會顯示接口對象中所有提供的類型、函數、對象以及對象中的方法和對象。
module.exports對外提供接口如何處理?
//mex.js
var ex_fn= function () {console.log('this in funtion ex_fn'); } module.exports=ex_fn;
調用代碼mex.js:
//引用mex.jsvar ex=require('./mex');
ex();
console.log(ex);
執行結果為:
?
?直接將函數作為返回。
再看下面一個例子:
var person={name :"person's name",age :20,getAge: function () {return this.age;} }module.exports = person;調用的代碼:
var person=require('./modulex');console.log(person.name); console.log(person.age); console.log(person.getAge()); console.log(person);顯示的結果為:
返回為一個json對象,可以直接調用內部的函數、屬性。
module.exports 與exports是什么關系?
?
module.exports = 'personname';exports.name=function () {console.log('this is person name'); }調用 的腳本:
var person=require('./person');console.log(person); console.log(person.name);執行結果:
personname
undefined
?
結果:
其實真正的接口是module.exports,exports是一個輔助工具。最終返回到是module.exports,而不是exports。
當module.exports沒有任何屬性和方法,exports將收集的所有信息都傳遞給module.exports,如果module.exports已經具有了屬性和方法,exports所搜集的信息將會被忽略。
轉載于:https://www.cnblogs.com/macoco/p/5398864.html
總結
以上是生活随笔為你收集整理的Node中Exports与module.export的使用与区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Swift]随slider变化而变化的
- 下一篇: 大班社会教案《我是中国娃》反思