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

相关推荐
阿黎梨梨11 小时前
AI也有记忆?LangChain Memory 管理指南
langchain·node.js·llm
小小龙学IT13 小时前
libuv 开源异步 I/O 事件循环库深度解析:Node.js 的心脏,C++ 高性能网络程序的引擎
c++·开源·node.js
用户672465366051 天前
Node 守护进程日志转发踩坑记:stdio 管道、UTF-8 截断,和一个字符串按值传参的故事
node.js
coderCN2 天前
Nodejs express+knex(ORM框架)
前端·node.js
coderCN2 天前
Nodejs mysql2+express+yaml
node.js
烬羽2 天前
我把"时间胶囊"部署上腾讯云宝塔,跨域从根源消失了
nginx·node.js·全栈
东风破_2 天前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
东风破_2 天前
danci 项目(三):从 JSON 数据到 AI Coding,真实项目里的数据清洗、Prompt 和工程规范
前端·后端·node.js
东风破_2 天前
danci 项目(一):从需求到架构,一个单词学习系统为什么会这样设计
前端·后端·node.js
__zRainy__2 天前
Node系列 · Express:常用的中间件
中间件·node.js·express