nodejs exports與module.exports的區別

來源:互聯網
上載者:User

標籤:代碼   var   屬性   module   調用   pre   指標   console   區別   

exports和module.exports的作用都是將檔案模板的方法和屬性暴露給require返回的對象進行調用。但是兩者有本質的區別,exports的屬性和方法都可以被module.exports替代。

如下代碼是一樣的:

exports.name=‘iwang‘module.exports.name = ‘iwang‘

但是exports不能替代module.exports的方法,所有的exports對象最終都是通過module.exports傳遞執行的。可以理解exports是給module.exports添加屬性和方法的。一開始module.exports是一個Null 物件。我們使用 require()返回的對象就是module.exports對象。

  檔案模板module.js 其實什麼都沒有寫單純列印module.exports

console.log(module.exports)

調用檔案模板index.js

var obj = require(‘/module‘)console.log(obj)  // {}

列印出的就是沒有屬性和方法的Null 物件。

看下面檔案代碼

module.exports = {    name:‘iwang‘,    age:26}exports.stature = 180console.log(module.exports) // { name: ‘iwang‘, age: 26 }

我們對module.exports 重新定義了這個對象。而不是對module.exportst添加屬性和方法。這樣做,打斷了module.exports和exports的關係。我們使用exports.stature添加了一個stature(身高)的屬性,並不管用。當我們使用下面做法,就沒有問題。

module.exports.name = ‘iwang‘;module.exports.age = 26;exports.stature = 180;console.log(module.exports) // { name: ‘iwang‘, age: 26, stature: 180 }

所以 我們可以理解 一開始 moudle.exports = exports = {},使用require返回的對象是module.exports。所以當我們重新定義module.exports為其他對象的指標。exports和module.exports再也沒有半毛錢關係。

只要大家上面理解紅色文字的話,就能區別module.exports和exports的關係了。

 

nodejs exports與module.exports的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.