gpt4 book ai didi

javascript - 为什么在为 module.exports 分配对象时这是一个空对象?

转载 作者:搜寻专家 更新时间:2023-11-01 00:47:46 25 4
gpt4 key购买 nike

我试图理解有关 Node.js 中的 this 关键字的一个简单概念。我的问题如下:

我知道 Node.js 中的 this 关键字指的是模块的范围,而不是全局命名空间。当通过 module.exports 定义模块时,this 的值应该改变。然而,根据我分配给 module.exports 的内容,结果是不同的,这是我不明白的。请查看以下代码块:

1 - 在第一个示例中,module.exports.nameOfModule 被分配了一个字符串。 this 指的是一个包含这个字符串的对象:

module.exports.nameOfModule = 'This Tutorial Module';

console.log(this);
// > { nameOfModule: 'This Tutorial Module' }

2 - 在第二个示例中,module.exports 被分配了一个对象。并且 this 确实引用了一个空对象。

module.exports = {
nameOfTheModule: 'This tutorial module.',
};

console.log(this);
// > {}

为什么会这样?为什么我在第二个示例中看不到 this 关键字中引用的已分配对象?提前致谢!

最佳答案

exports 变量在模块的文件级范围内可用,并在评估模块之前分配 module.exports 的值。

It allows a shortcut, so that module.exports.f = ... can be written more succinctly as exports.f = .... However, be aware that like any variable, if a new value is assigned to exports, it is no longer bound to module.exports: node ref

当您在 module.exports 上添加一个键时,它不会覆盖它

enter image description here

但是当你分配一个完整的新值时 module.exports = 'some value' 它不一定是 module.exports 它掩盖了 exports 具有新的值(value),

enter image description here

关于javascript - 为什么在为 module.exports 分配对象时这是一个空对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027828/

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