[英]Nodejs module exports confusion
我對module.exports感到困惑。 據我了解, module.exports
是暴露給其他模塊的對象,
exports=module.exports={}
但是在node.js的morgan包的index.js中,我發現了這一點。
module.exports = morgan
module.exports.compile = compile
module.exports.format = format
module.exports.token = token
morgan
, compile
, format
和token
都是函數。
您能解釋一下這里發生了什么嗎? 一個函數(摩根)如何分配給module.exports? 在執行第一行之后,module.exports是函數而不是JSON對象嗎?
Node模塊基本上是這樣的:
var module = {
exports: {}
};
(function (exports, require, module, __filename, __dirname) {
// your module code here
})(module.exports, require, module, __filename, __dirname);
var exported = module.exports;
默認情況下, exports
和module.exports
都指向同一個對象。 您可以像往常一樣向對象添加屬性。 但是,如果要返回函數或其他對象而不是默認的標准對象怎么辦?
在這種情況下,您可以將module.exports
設置為其他內容,這將是新的導出對象。
module.exports = function() {};
當然,該函數也可以具有屬性,因此您的代碼有點像這樣:
module.exports = function(){};
module.exports.compile = function() {};
module.exports.format = function() {};
module.exports.token = function() {};
相當於:
var morgan = function() {};
var compile = function() {};
var format = function() {};
var token = function() {};
morgan.compile = compile;
morgan.format = format;
morgan.token = token;
module.exports = morgan;
一個函數(摩根)如何分配給module.exports? 在執行第一行之后,module.exports是函數而不是JSON對象嗎?
是的, module.exports
將是一個函數,代替默認對象(但是這里沒有JSON,JSON不是JavaScript對象,而是一種編碼格式)。
您可能需要閱讀以下答案以獲得更深入的說明:
Morgan只是向正在導出的模塊中添加參數(在這種情況下為compile
, format
和token
。當您使用morgan = require('morgan')
類的東西在應用程序中需要該模塊時,您可以調用morgan.format
返回附加到對象的格式。
希望能把事情弄清楚!
您能解釋一下這里發生了什么嗎?
分配聲明正在發生。
// path-to-my-module.js
module.exports = morgan
module.exports.compile = compile
module.exports.format = format
module.exports.token = token
對於這4條語句中的每條語句,都有一個賦值語句。 看第一行, module.exports = morgan
,這意味着module.exports
對象將具有一個名為morgan
的屬性,其值是標識符morgan
的值
因此,當您像這樣使用它時:
var m = require('./path-to-my-module.js');
console.log(m.morgan);
console.log(m);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.