NodeJs中Module.exports和exports

Node.js中的何時用module.exports,何時用exports,區別是什麼html

官方文檔的一開頭,給出的例子是這樣的:
http://nodejs.org/api/modules.html
node

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

 

var PI = Math.PI;
exports.area = function (r) {
  return PI * r * r;
};


官方文檔中的另外一段話:api

引用
As a guideline, if the relationship between exports and module.exports seems like magic to you, ignore exports and only use module.exports.
當你對module.exports和exports的關係感到困惑的時候,一直使用module.exports,而且忽略exports


因而問題出來了,module.exports是怎麼回事兒?咱們何時使用module.exports,何時使用exports呢?

若是你的模塊屬於「模塊實例(module instances)」,就像官方文檔中給出的示例那樣,那麼exports足以知足要求。

可是事實上,require()返回的是module.exports,exports只是module.exports的一個引用,exports的做用只在module.exports沒有指定的時候,收集屬性並附加到module.exports。ide

引用
The exports variable that is available within a module starts as a reference to module.exports.



你的模塊老是返回module.exports,而不是exports。

ui

module.exports = '孫悟空';
exports.name = function() {
    console.log('我是白骨精');
};


這個模塊會徹底忽略exports.name,由於module.exports被指定了另外一個對象。你的模塊不必定是模塊實例(module instances),你的模塊能夠是任意的,你設置成module.exports的Javascript對象。若是你不顯示的指定module.exports,那麼返回的將是exports和exports附加的值。

也能夠這樣認爲,一個模塊剛開始的時候,module.exports和exports是同樣的,exports只是module.exports的一個別名,二者都是{}。

當你給module.exports指定一個對象的時候,二者就再也不同樣的,而模塊導出的必定是module.exports。

若是你想你的模塊是指定的一種對象類型,那就使用module.exports,若是你想讓你的模塊是典型的模塊實例,那就用exports就能夠了。

下面介紹一種module.exports的典型用法,將模塊導出來類或者對象。

在Javascript中建立對象有多種方式。spa

引用
《JavaScript高級程序設計(第3版)》第6章第2節


咱們使用其中介紹的第三種方式——原型模式來建立一個對象

prototype

function Person(){
}
Person.prototype.sayName = function(){
    console.log('我叫唐僧');
};
module.exports = new Person();


在其餘代碼中require引用此模塊時,將返回一個Person的對象,並調用其中的方法。設計

var person = require('./person');
person.sayName();


固然也能夠用code

module.exports = Person;

導出Person,在須要時候使用htm

var Person = require('./person');
var person = new Person();
person.sayName();


來建立對象。

 

 

這個東西其實相似:

var o = { a: 1}, b = o, c = { b: 2}; b;// {a:1} b = c; b;//{b:2} o;//{a:1} 


賦值不會改變引用參數,即對b賦值,不管何值,o不受影響,但改變b的屬性,o就受影響了,exports和module.exports就這麼一個意思,對exports賦值,沒法影響module.exports的值,但對exports.xxx賦值能夠,對module.exports賦值,則能夠覆蓋exports。由於exports是指向module.exports的。

相關文章
相關標籤/搜索