NodeJS中模組匯出兩種方式【exports和module.exports】的聯絡與區別
阿新 • • 發佈:2021-08-07
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' }
本文來自部落格園,作者:lvhanghmm,轉載請註明原文連結:https://www.cnblogs.com/lvhanghmm/p/15111233.html