日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Node中Exports与module.export的使用与区别

發布時間:2023/12/19 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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.js

exports='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.js

var 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的使用与区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。