gpt4 book ai didi

javascript - Nodejs 模块导出困惑

转载 作者:行者123 更新时间:2023-11-30 09:49:05 24 4
gpt4 key购买 nike

我对 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 and token 都是函数。

你能解释一下这里发生了什么吗?函数( morgan )如何分配给 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;

默认情况下,exportsmodule.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;

How is a function(morgan) assigned to module.exports ? After the first line is executed, is module.exports a function instead of an JSON object?

是的,module.exports会是一个函数,代替默认对象(不过这里没有JSON,JSON不是JavaScript对象,而是一种编码格式)。

关于javascript - Nodejs 模块导出困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37397089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com