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

相关推荐
青灬河3 小时前
实现企业级全栈应用服务框架-Elpis(一)
vue.js·node.js
星空下的曙光5 小时前
Node.js events模块所有 API 详解 + 常用 API + 使用场景
node.js
无责任此方_修行中5 小时前
我的两次 Vibe Coding 经历,一次天堂,一次地狱
后端·node.js·vibecoding
程序铺子10 小时前
如何使用 npm 安装 sqlite3 和 canvas 这些包
javascript·npm·node.js
星空下的曙光11 小时前
Node.js 事件循环(Event Loop)
node.js
勤奋菲菲1 天前
Egg.js 完全指南:企业级 Node.js 应用框架
开发语言·javascript·node.js
aesthetician1 天前
Node.js 24.10.0: 拥抱现代 JavaScript 与增强性能
开发语言·javascript·node.js
APItesterCris1 天前
Node.js/Python 实战:编写一个淘宝商品数据采集器
大数据·开发语言·数据库·node.js
勤奋菲菲2 天前
Koa.js 完全指南:下一代 Node.js Web 框架
前端·javascript·node.js
少年阿闯~~2 天前
Node.js核心模块:fs、path与http详解
node.js