導出功能爲 '先進' 使用 module.exports
系統。想想這樣說:
1.
簡單模塊可導出文本值[易peasy]:
// file1.js
module.exports = 12;
// file2.js
var x = require('file1.js');
console.log(x); // 12
2.
一個模塊那導出函數[在被調用之前什麼也不做]]:
// file3.js
module.exports = function() {
console.log('somebody run me');
}
// file4.js
var x = require('file3.js');
console.log(x); // oops a [function]
// ... but
console.log(x()); // yay; somebody run me
3。
一個模塊該出口被調用的函數[便於終端用戶]:
// file5.js
module.exports = function() {
console.log('somebody run me, now');
}();
// file5.js
var x = require('file5.js');
console.log(x); // somebody run me, now
4.
最後,一個模塊一個導出一個可調用功能,在需要的參數[更復雜,但更靈活]:
// file6.js
module.exports function (foo) {
return "foo-" + foo;
};
// file7.js
var x = require('file6.js');
var result = x('something');
console.log(result); // foo-something
爲什麼我不需要引用'.user',其中包含email()fn? – Marodian
@Marodian - 你顯然有一種誤解,認爲函數內部聲明的局部變量在某種程度上可以作爲函數的屬性訪問,而不執行該函數。這在Javascript中完全不成立。一個局部變量在一個函數之外是不可訪問的,你聲明你的模塊的方式是它所導出的所有函數。要獲得'user'對象,你必須執行那個函數。然後,該函數返回一個具有'.email'屬性的對象。 – jfriend00