node.js 05--module.exports和exports的功能和区别

敲重点

require引入模块永远为++module.exports++ 指向的++对象++

一.使用方法

javascript 复制代码
//声明一个对象
const s = {
    name:'张三',
    age:22
}

//导出这个模块
exports = s

//导出这个模块
module.exports = s
javascript 复制代码
const ex = require('./01-exports')

console.log(ex) //输出 { name: '张三', age: 22 }

这时候module.exports和exports指向的是一个对象,都是s这个对象

javascript 复制代码
//声明一个对象
const s = {
    name:'张三',
    age:22
}

//导出这个模块
exports = s

//导出这个模块
module.exports.gender = '女'

如果换成了上面这种的话

javascript 复制代码
const ex = require('./01-exports')

console.log(ex) //输出 { gender: '女' }

这时候exports指向的对象为s,但module.exports指向的对象为gender所在的这个对象

因为require导入的模块永远以module.exports指向的对象为基准,所以输出gender所在的那个对象

有人可能说那有可能跟执行顺序有关系,其实换成下面这种结果也不会发生改变

javascript 复制代码
//声明一个对象
const s = {
    name:'张三',
    age:22
}

//导出这个模块
module.exports.gender = '女'

//导出这个模块
exports = s

但如果变成下面这种

javascript 复制代码
//导出这个模块
exports.name = '张三'

//导出这个模块
module.exports.gender = '女'

那么输出的将会是

javascript 复制代码
const ex = require('./01-exports')

console.log(ex) //输出{ name: '张三', gender: '女' }

因为++exports本身与module.exports指向的就是同一个对象++,所以当没有指向其他对象而是直接往当前指向对象中赋值的时候,指向的对象并没有发生改变,所以输出的也是同一个对象

那么换成下面这种情况

javascript 复制代码
// 声明一个对象
const s = {
  name: '张三',
  age: 22
}

//导出这个模块
exports = s

//导出指向exports模块
module.exports = exports

//往exports所指向的对象中添加属性
module.exports.gender = '女'
javascript 复制代码
const ex = require('./01-exports')

console.log(ex) //输出 { name: '张三', age: 22, gender: '女' }

因为这里module.exports指向的对象变为了exports所指向的对象,因此module.exports所指向的对象变为了s,最后往s添加了一条属性gender,所以输出为三个属性数据

相关推荐
Stream_Silver1 天前
【Node.js 安装报错解决方案:解决“A later version of Node.js is already installed”问题】
node.js
Anthony_2311 天前
基于 Vue3 + Node.js 的实时可视化监控系统实现
node.js
说给风听.1 天前
解决 Node.js 版本冲突:Windows 系统 nvm 安装与使用全指南
windows·node.js
森叶2 天前
Node.js 跨进程通信(IPC)深度进阶:从“杀人”的 kill 到真正的信号
node.js·编辑器·vim
虹科网络安全2 天前
艾体宝新闻 | NPM 生态系统陷入困境:自我传播恶意软件在大规模供应链攻击中感染了 187 个软件包
前端·npm·node.js
摇滚侠2 天前
PNPM 包管理工具和 NPM 包管理工具
vscode·npm·node.js·pnpm
心柠2 天前
webpack
前端·webpack·node.js
FreeBuf_2 天前
vm2 Node.js库曝严重沙箱逃逸漏洞(CVE-2026-22709)可导致任意代码执行
node.js
147API2 天前
改名后的24小时:npm 包抢注如何劫持开源项目供应链
前端·npm·node.js
抵梦2 天前
NPM、CNPM、PNPM:Node.js 依赖工具对比与选择
前端·npm·node.js