哪里有网站建设联系方式,网站备案不注销有什么后果,郑州专门做网站的公司有哪些,南宁网站排名外包在Node.js中#xff0c;module.exports 和 exports 是两种导出模块的方式#xff0c;它们的作用是使得模块中的内容可以被其他模块引用和使用。
module.exports: module.exports 是一个指向当前模块所导出内容的对象的引用。你可以通过给 module.exports 赋值来导出一个对象…在Node.js中module.exports 和 exports 是两种导出模块的方式它们的作用是使得模块中的内容可以被其他模块引用和使用。
module.exports: module.exports 是一个指向当前模块所导出内容的对象的引用。你可以通过给 module.exports 赋值来导出一个对象、函数、类或者任何其他的JavaScript类型。
// example.js
module.exports {foo: bar,baz: function() {console.log(baz);}
};exports: exports 是 module.exports 的一个引用它是一个特殊的变量指向了 module.exports。
// example.js
exports.foo bar;
exports.baz function() {console.log(baz);
};不要同时使用exports和module.exports
虽然 exports 和 module.exports 都可以用来导出内容但是在同一个模块中不应该同时使用它们。因为在模块加载完成后Node.js 会返回 module.exports 而不是 exports。如果你同时使用了它们但只有其中一个被赋值那么最终导出的内容只会是 module.exports 所指向的对象而 exports 上的属性将被忽略。
// example.js
// 此处使用 exports 导出变量
exports.baz function() {console.log(baz);
};
// 此处使用 module.exports 导出对象
module.exports {foo: bar
};当在同一个模块中同时使用 module.exports 和 exports 时只有 module.exports 的赋值会生效而 exports 上的属性将被忽略。这可能会导致一些意想不到的结果。下面是一个示例来说明这一点
// example.js
// 此处使用 module.exports 导出对象
module.exports {foo: bar
};// 此处使用 exports 导出变量
exports.baz function() {console.log(baz);
};在上面的例子中module.exports 导出了一个对象 { foo: bar }而 exports 导出了一个函数 baz。但是由于最终模块导出的是 module.exports 所指向的对象而不是 exports所以 exports 上的属性不会被导出。
因此在这个例子中其他模块引入 example.js 后只能访问到 foo而不能访问到 baz。
正确的做法是要么只使用 module.exports要么只使用 exports。
不要直接给exports赋值
exports正确的用法是给他添加属性如果直接赋值将会导出空对象。
exports是module.export的一个引用。给exports添加属性就等于是给module.exports添加属性直接给exports赋值就改变了变量exports的指向就是说exports不再是module.exports的引用。那么此时module.exports就是空对象。
// example.js
exports123导入example.js模块的文件得到的是一个空对象。这是因为只有 module.exports 指向的对象才会被导出而不是 exports