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

相关推荐
李游Leo11 小时前
Node.js 多版本管理与 nvm/nvs 使用全流程(含国内镜像加速与常见坑)
node.js
Q_Q196328847512 小时前
python+springboot+uniapp微信小程序题库系统 在线答题 题目分类 错题本管理 学习记录查询系统
spring boot·python·django·uni-app·node.js·php
陈随易17 小时前
适合中国宝宝的AI编程神器,文心快码
前端·后端·node.js
Q_Q196328847520 小时前
python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
开发语言·spring boot·python·django·flask·node.js·php
EndingCoder21 小时前
Electron 新特性:2025 版本更新解读
前端·javascript·缓存·electron·前端框架·node.js·桌面端
machinecat1 天前
node,小程序合成音频的方式
前端·node.js
草木红1 天前
express 框架基础和 EJS 模板
arcgis·node.js·express
亮子AI2 天前
【npm】npm 包更新工具 npm-check-updates (ncu)
前端·npm·node.js
Yvonne爱编码2 天前
构建高效协作的桥梁:前后端衔接实践与接口文档规范详解
前端·git·ajax·webpack·node.js
Juchecar2 天前
AI教你常识之 ESM + Express + Vue3 + CSV文件 + Pinia + CRUD
node.js