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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

node.js中exports与module.exports的区别分析

發布時間:2023/12/2 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 node.js中exports与module.exports的区别分析 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

前言

關于Node.js中的exports和module.exports,很多時候都比較容易讓人混淆,弄不清楚兩者間的區別。那么我們就從頭開始理清這兩者之間的關系。

來源

在開發Node.js應用的時候,很多模塊都是需要引入才能使用,但是為什么exports和module.exports我們沒有引用卻可以直接使用呢?

事實上,Node.js應用在編譯的過程中會對JavaScript文件的內容進行頭尾的封裝。例如:

// hello.js const hello = function () {console.log('Hello world'); } module.exports = {hello } // 頭尾封裝后的js代碼 (function (exports, require, module, __filename, __dirname) {const hello = function () {console.log('Hello world');}module.exports = {hello} })

在進行了頭尾封裝之后,各個模塊之間進行了作用域隔離,避免了污染全局變量,同時可以使每個模塊在不引入這些變量的情況下可以使用它們。這些變量依次為當前模塊的exports屬性、require()方法、當前模塊自身(module)、在文件系統中的完整路徑、文件目錄。

區別

按照Node.js的解釋,exports是module對象的一個屬性,那么exports和module.exports應該是等價的。的確如初,初始化的exports和module.exports變量的值均為{},代碼驗證:

// hello.js const hello = function () {console.log('Hello world'); } console.log('初始值=========='); console.log(exports); console.log(module.exports); module.exports = {hello } // 輸出結果 初始值========== {} {}

可以發現,module對象的exports屬性和exports均指向一個空對象{},那么在導出對象的時候使用exports和module.exports有什么區別呢?

我們在使用require()方法引入模塊的時候,其實是引入了module.exports對象, exports只是module對象的exports的一個引用,我們可以通過修改exports所指向對象的值來協助修改module.exports的值。

  • 使用exports導出
const hello = function () {console.log('Hello world'); } exports.hello = {hello } console.log('修改值=========='); console.log(exports); console.log(module.exports); // 輸出結果 修改值========== { hello: { hello: [Function: hello] } } { hello: { hello: [Function: hello] } }

由于exports和module.exports指向同一塊內存區域,所以我們修改exports對象的數據,那么module.exports也會隨之改變。

  • 使用module.exports導出
// hello.js const hello = function () {console.log('Hello world'); } module.exports = {hello } console.log('修改值=========='); console.log(exports); console.log(module.exports); // 輸出結果 修改值========== {} { hello: [Function: hello] }

你會發現修改后的exports依然是{},而module.exports的值已經改變,這是由于當你給module.exports是直接等于一個新的對象,那么其將指向一塊新的內存區域,而此時exports指向的仍然是之前的內存區域,所以二者的值會不一樣,但是此時你在其他文件內引入hello.js文件,仍然可以調用hello()方法,這也說明了導出的是module.exports而不是exports。

  • 給exports直接賦值
// hello.js const hello = function () {console.log('Hello world'); } exports = {hello } console.log('修改值=========='); console.log(exports); console.log(module.exports); // 輸出結果 修改值========== { hello: [Function: hello] } {}

使用這種方法導出在其他文件調用hello方法即會報錯,因為該文件模塊導出的對象為空,當然也不可能有hello()方法,這種問題的原因同樣是指向的內存區域發生變化所導致的。

總結

  • exports對象是module對象的一個屬性,在初始時exports和module.exports是指向同一塊內存區域的;
  • 在不改變exports內存指向的情況下,修改exports的值可以改變module.exports的值;
  • 導出盡量使用module.exports以避免混淆。
  • 總結

    以上是生活随笔為你收集整理的node.js中exports与module.exports的区别分析的全部內容,希望文章能夠幫你解決所遇到的問題。

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