gpt4 book ai didi

javascript - Expressjs JavaScript 基础 : exports = module. exports = createApplication;

转载 作者:搜寻专家 更新时间:2023-10-31 23:54:54 24 4
gpt4 key购买 nike

我不知道这个模式叫什么,如果我知道我会直接查找它。

主要是,这是如何工作的? (这段代码取自Express.js)

exports = module.exports = createApplication;

我以前在有这种类型的引用变量链ex的地方看到过类似的模式:

x = y = z

我了解 exports 与 module.exports,但查看上面的模式让我质疑它实际上是如何工作的。

我遵循的一般经验法则是“module.exports”是真正的交易,而“exports”是它的助手,更多信息 here

模块模式是这样的吗(不改变 module.exports)?

exports = module.exports = {};

例如:

exports.name = 'hello' 

结果

exports = module.exports = {name: 'hello'}

当您更改导出的引用时会发生什么?

exports = {name: 'bob'}

现在,当您添加到 exports 时,它将引用 `{name: 'bob'} 并且不再与 module.exports 有任何联系?

最佳答案

您的直觉是正确的。我将自下而上地工作:

Node.js 包装器

在运行任何文件之前,Node.js wraps the entire scriptimmediately-invoked function expression (IIFE) :

(function (exports, require, module, __filename, __dirname) {
// ...script goes here...
});

这就是它将 moduleexports 变量引入作用域的方式;它们与函数参数没有什么不同。

使用导出

关于 module.exportsexports 别名的 Node.js 文档非常有用。首先,module.exportsexports 变量都引用由模块系统创建的同一个空对象。

如果一个模块只需要导出一个带有一些属性集的普通旧 JavaScript 对象,exports 就足够了:

exports.get = function(key) {
// ...
};

exports.set = function(key, value) {
// ...
};

当代码 require() 这个模块时,结果将类似于:

{
get: [Function],
set: [Function]
}

替换 module.exports

但是,Express 导出构造函数 createApplication 作为根值。要导出函数本身,而不是仅仅将其分配给导出对象的属性,它必须首先完全替换导出的对象:

module.exports = createApplication;

现在,exports 还没有更新,仍然引用旧对象,而 module.exports 是对 createApplication 的引用。但是if you keep reading ,您会注意到 Express 除了构造函数外还导出其他几个属性。虽然将这些分配给 module.exports 的新值的属性就足够了,但重新分配 exports 更短,因此它再次成为 的别名module.exports,然后在 exports 上分配这些属性,这等同于在 module.exports 上分配它们。

因此,这些示例在功能上是等效的:

module.exports = createApplication;

function createApplication() {
// ...
}

module.exports.application = proto;
module.exports.request = req;
module.exports.response = res;

但是这个不那么冗长:

exports = module.exports = createApplication;

function createApplication() {
// ...
}

exports.application = proto;
exports.request = req;
exports.response = res;

无论哪种方式,结果都是一样的,在根目录中有一个名为 createApplication 的函数,其上有可用的属性:

{
[Function: createApplication]
application: [Object],
request: [Object],
response: [Object],
// ...a few other properties...
}

关于javascript - Expressjs JavaScript 基础 : exports = module. exports = createApplication;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509162/

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