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,所以输出为三个属性数据

相关推荐
前端双越老师1 天前
如何以前端视角(非0基础)学 Java ?
java·node.js·全栈
Kel1 天前
Node.js 没那么复杂
人工智能·node.js·全栈
星栈独行1 天前
Node 接口该写同步还是异步?
服务器·开发语言·后端·程序人生·node.js
星栈2 天前
Node 接口该写同步还是异步?
后端·node.js
半个落月2 天前
用 LangChain 连接远程 MCP:从工具发现到多轮调用闭环
人工智能·后端·node.js
星栈独行2 天前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·程序人生·node.js
徐小超2 天前
从一句 Hello World 到完整 RAG 系统:一个 AI 知识库的架构选型实录
langchain·node.js·ai编程
雷工笔记3 天前
如何查看电脑有没有安装node.js及如何安装node.js
node.js
星栈3 天前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·node.js
万敏3 天前
Vue3 全栈实战第三周:组件化开发完整记录 —— Props / Emit / provide-inject / 插槽 / 自定义指令
vue.js·node.js·全栈