sách gpt4 ai đã đi

javascript - CommonJs模块系统中 "module.exports"和 "exports"之间的区别

In lại 作者:太空宇宙 更新时间:2023-11-04 01:58:22 29 4
mua khóa gpt4 Nike

在此页面 ( http://docs.nodejitsu.com/articles/getting-started/what-is-require ) 上,它指出“如果要将导出对象设置为函数或新对象,则必须使用 module.exports 对象。”

我的问题是为什么。

// right
module.exports = function () {
console.log("hello world")
}
// wrong
exports = function () {
console.log("hello world")
}

我通过 console.logged 结果 (result=require(example.js)),第一个是 [Function],第二个是 {}.

您能解释一下背后的原因吗?我在这里读了这篇文章:module.exports vs exports in Node.js 。它很有帮助,但没有解释为什么这样设计。直接返回exports的引用会有问题吗?

1 Câu trả lời

mô-đun 是一个带有 exports 属性的纯 JavaScript 对象。 exports 是一个纯 JavaScript 变量,恰好设置为 module.exports。在文件末尾,node.js 基本上会将 module.exports“返回”到 require 函数。在 Node 中查看 JS 文件的简化方法可能是这样的:

var module = { exports: {} };
var exports = module.exports;

// mã của bạn

return module.exports;

如果您在 exports 上设置属性,例如 exports.a = 9;,也会设置 module.exports.a,因为对象在 JavaScript 中作为引用传递,这意味着如果您为同一个对象设置多个变量,它们都是同一个对象;所以 exportsmodule.exports 是同一个对象。
但是,如果您将 exports 设置为新的内容,它将不再设置为 module.exports,因此 exportsmodule.exports 不再是同一个对象。

关于javascript - CommonJs模块系统中 "module.exports"和 "exports"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46971086/

29 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com