首页 > Web开发 > 详细

NodeJS中模块导出两种方式【exports和module.exports】的联系与区别

时间:2021-08-07 14:53:48      阅读:31      评论:0      收藏:0      [点我收藏+]

NodeJS中模块导出两种方式的联系与区别

exports是module.exports的别名(地址引用关系)【也就是说 他们两个都指向同一个地址!】,导出对象最终以module.exports为准【如果都指向同一个属性,那么导出的结果将以module.exports为准!】

栗子:

将上面的栗子稍作修改!

module.exports.js

const greeting = name => {
    return `hello ${name}!`
}

const x = 100000;
const y = ‘dapeng‘;

exports.y = y;
exports.x = x;
module.exports.x = 100;
module.exports.greeting = greeting;

require.js

const a = require(‘./module.exports‘);

// console.log(a.greeting(‘lvhanghmm‘))
console.log(a)

技术分享图片

你看,他们都导出各自的数据,但是当他们都指向同一个属性的时候最后的导出结果是以module.exports为准偶!

还有一点就是当他们两个指向的不是同一个对象的时候,也是以module.exports为准偶!

module.exports

const greeting = name => {
    return `hello ${name}!`
}

const x = 100000;
const y = ‘dapeng‘;
exports.y = y;
exports.x = x;
module.exports.x = 100;
module.exports.greeting = greeting;

module.exports = {
    username: ‘lvhanghmm‘
}

技术分享图片

NodeJS中模块导出两种方式【exports和module.exports】的联系与区别

原文:https://www.cnblogs.com/lvhanghmm/p/15111233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!