NodeJS中模塊導出兩種方式【exports和module.exports】的聯系與區別


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'
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM