Node.js中exports與module.exports的區別

來源:互聯網
上載者:User

標籤:另一個   string   應該   調用   module   eth   nod   out   node.js   

你肯定對Node.js模組中用來建立函數的exports對象很熟悉(假設一個名為rocker.js的檔案):

exports.name = function() {    console.log(‘My name is Lemmy Kilmister‘);};

然後你在另一個檔案中調用:

var rocker = require(‘./rocker.js‘);rocker.name(); // ‘My name is Lemmy Kilmister‘

但是module.exports到底是個什麼玩意兒? 它合法嗎?

令人吃驚的是-module.exports是真實存在的東西。exports只是module.exports的輔助方法。你的模組最終返回module.exports給調用者,而不是exports。exports所做的事情是收集屬性,如果module.exports當前沒有任何屬性的話,exports會把這些屬性賦予module.exports。如果module.exports已經存在一些屬性的話,那麼exports中所用的東西都會被忽略。

把下面的內容放到rocker.js:

module.exports = ‘ROCK IT!‘;exports.name = function() {    console.log(‘My name is Lemmy Kilmister‘);};

然後把下面的內容放到另一個檔案中,執行它:

var rocker = require(‘./rocker.js‘);rocker.name(); // TypeError: Object ROCK IT! has no method ‘name‘

rocker模組完全忽略了exports.name,然後返回了一個字串’ROCK IT!’。通過上面的例子,你可能認識到你的模組不一定非得是模組執行個體(module instances)。你的模組可以是任何合法的JavaScript對象 - boolean,number,date,JSON, string,function,array和其他。你的模組可以是任何你賦予module.exports的值。如果你沒有明確的給module.exports設定任何值,那麼exports中的屬性會被賦給module.exports中,然後並返回它。

在下面的情況下,你的模組是一個類:

module.exports = function(name, age) {    this.name = name;    this.age = age;    this.about = function() {        console.log(this.name +‘ is ‘+ this.age +‘ years old‘);    };};

然後你應該這樣使用它:

var Rocker = require(‘./rocker.js‘);var r = new Rocker(‘Ozzy‘, 62);r.about(); // Ozzy is 62 years old

在下面的情況下,你的模組是一個數組:

module.exports = [‘Lemmy Kilmister‘, ‘Ozzy Osbourne‘, ‘Ronnie James Dio‘, ‘Steven Tyler‘, ‘Mick Jagger‘];

然後你應該這樣使用它:

var rocker = require(‘./rocker.js‘);console.log(‘Rockin in heaven: ‘ + rocker[2]); //Rockin in heaven: Ronnie James Dio

現在你應該找到要點了 - 如果你想要你的模組成為一個特別的物件類型,那麼使用module.exports;如果你希望你的模組成為一個傳統的模組執行個體(module instance),使用exports。

把屬性賦予module.exports的結果與把屬性賦予給exports是一樣的。看下面這個例子:

module.exports.name = function() {    console.log(‘My name is Lemmy Kilmister‘);};

下面這個做的是一樣的事情:

exports.name = function() {    console.log(‘My name is Lemmy Kilmister‘);};

但是請注意,它們並不是一樣的東西。就像我之前說的module.exports是真實存在的東西,exports只是它的輔助方法。話雖如此,exports還是推薦的對象,除非你想把你模組 的物件類型從傳統的模組執行個體(module instance)修改為其他的。

Node.js中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.