gpt4 book ai didi

javascript - node.js 模块导出

转载 作者:行者123 更新时间:2023-11-30 07:17:15 26 4
gpt4 key购买 nike

这是什么原因:

exports.foo = 'foo';

var bar = require('./foo');
console.log(bar); // {foo: 'foo'}

但这不是:

var data = { foo: 'foo' };
exports = data;

var bar = require('./foo');
console.log(bar); // {}
// expected {foo: 'foo'}

最佳答案

我将尝试将其作为 javascript 问题来回答代码示例

function a() {}
a.prototype.foo = {test:"bar"}
var d = new a();
var c = new a();
console.log(d.prototype ==== c.prototype) // Both c and d share the same prototype object
d.foo.hai = "hello"
console.log(d.prototype ==== c.prototype) // Still the they refer to the same
d.foo = {im: "sorry"}
console.log(d.prototype ==== c.prototype) // now they don't

Node 相同

console.log(module.exports === exports);// true; They refer to the same object
exports.a = {tamil: "selvan"}
console.log(module.exports === exports);// true even now

exports = {sorry: "im leaving"}; // overrides modules.exports
console.log(module.exports === exports); //false now they don't
console.log(module.exports); // {a: {tamil: "selvan"}}
console.log(exports); // {sorry: "im leaving"}

exports 和 module.exports 引用相同的核心对象,直到您像在 javasacript 原型(prototype)对象中一样进行覆盖。在您覆盖引用更改的那一刻。

module.exports = {something: "works"} 之所以有效,是因为您正在更改 Node 在缓存时关心的模块的属性。

即使是上面的

module.exports === exports//为假,它们不再相同

这证明反之亦然:)

还有一件事 module 是对当前模块的引用,所以总是更喜欢使用 module.exports 而不是 exports

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

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