欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > node.js 05--module.exports和exports的功能和区别

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

2025/5/12 0:10:28 来源:https://blog.csdn.net/m0_63541756/article/details/144283001  浏览:    关键词:node.js 05--module.exports和exports的功能和区别

敲重点

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

一.使用方法

//声明一个对象
const s = {name:'张三',age:22
}//导出这个模块
exports = s//导出这个模块
module.exports = s
const ex = require('./01-exports')console.log(ex) //输出 { name: '张三', age: 22 }

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

//声明一个对象
const s = {name:'张三',age:22
}//导出这个模块
exports = s//导出这个模块
module.exports.gender = '女'

如果换成了上面这种的话

const ex = require('./01-exports')console.log(ex) //输出 { gender: '女' }

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

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

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

//声明一个对象
const s = {name:'张三',age:22
}//导出这个模块
module.exports.gender = '女'//导出这个模块
exports = s

但如果变成下面这种

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

那么输出的将会是

const ex = require('./01-exports')console.log(ex) //输出{ name: '张三', gender: '女' }

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

那么换成下面这种情况

// 声明一个对象
const s = {name: '张三',age: 22
}//导出这个模块
exports = s//导出指向exports模块
module.exports = exports//往exports所指向的对象中添加属性
module.exports.gender = '女'
const ex = require('./01-exports')console.log(ex) //输出 { name: '张三', age: 22, gender: '女' }

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词