exports 和 module.exports 的区别
来源:互联网 发布:鲨鱼网络 编辑:程序博客网 时间:2024/06/11 17:35
require 用来加载代码,而 exports 和 module.exports 则用来导出代码。但很多新手可能会迷惑于 exports 和 module.exports 的区别,为了更好的理解 exports 和 module.exports 的关系,我们先来巩固下 js 的基础。示例:
test.js
var a = {name: 1};var b = a;
console.log(a);console.log(b);
b.name = 2;console.log(a);console.log(b);
var b = {name: 3};console.log(a);console.log(b);
运行 test.js 结果为:
{ name: 1 }{ name: 1 }{ name: 2 }{ name: 2 }{ name: 2 }{ name: 3 }
解释:a 是一个对象,b 是对 a 的引用,即 a 和 b 指向同一块内存,所以前两个输出一样。当对 b 作修改时,即 a 和 b 指向同一块内存地址的内容发生了改变,所以 a 也会体现出来,所以第三四个输出一样。当 b 被覆盖时,b 指向了一块新的内存,a 还是指向原来的内存,所以最后两个输出不一样。
明白了上述例子后,我们只需知道三点就知道 exports 和 module.exports 的区别了:
- module.exports 初始值为一个空对象 {}
- exports 是指向的 module.exports 的引用
- require() 返回的是 module.exports 而不是 exports
现在我们来看 Node.js 官方文档的截图:我们经常看到这样的写法:
exports = module.exports = somethings
上面的代码等价于:
module.exports = somethingsexports = module.exports
原理很简单,即 module.exports 指向新的对象时,exports 断开了与 module.exports 的引用,那么通过 exports = module.exports 让 exports 重新指向 module.exports 即可。
- exports 和 module.exports 的区别
- [前端] exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- nodejs exports和module.exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- module.exports和exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports和module.exports的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- exports 和 module.exports 的区别
- 样式加载不出来,浏览器控制台报错:Resource interpreted as Stylesheet but transferred with MIME type text/html
- 【笔记】《WebGL编程指南》学习-第5章颜色与纹理(3-使用多幅纹理))
- File IO(NIO.2):文件操作
- Reproducing and learning new algebraic operations on word embeddings using genetic programming
- hdu 2066 一个人的旅行
- exports 和 module.exports 的区别
- nginx 配置备忘
- nginx相关
- Java——反射
- ionic1.x 版本的透明状态栏的实现
- Intel SGX
- 报错The project was not built due to "A resource exists with a different case: '/xxx/bin/classes/com
- 【安全牛学习笔记】SSL、TLS中间人攻击
- JS不允许手动设置请求头的cookie