环境
exports与module.exports是必须运行在node环境下面的
引入方式
require
1 | let a = require('./a') |
使用方式
- 初始值
1 | console.log(exports) //{} |
从上面可知,一开始两者都是空对象,并且指向同一块内存
变化
- exports,只是一个变量名
1
2
3
4
5
6
7
8
9//a.js
function a() {
console.log(1)
}
exports.a = a
//b.js
let a = require('./a')
a.a() //1
console.log(a) //{ a: [Function: a] }- module.exports
1
2
3
4
5
6
7
8
9
10//a.js
function a() {
console.log(1)
}
module.exports = a
//b.js
let a = require('./a')
a() //1
console.log(a) //[Function: a]1
2
3
4
5
6
7
8
9//a.js
function a() {
console.log(1)
}
module.exports.a = a
//b.js
let a = require('./a')
a.a() //1
console.log(a) //{ a: [Function: a] }由于exports是一个空对象,在使用的时候,需要exports.xxx=xxxx,相当于给空对象添加一个属性,require之后,得到一个对象**{ a: [Function: a] },而module.exports使用方式可以选择直接赋值module.exports = a**,也可以使用module.exports.a = a,require引入的对象本质是module.exports。所以,exports不能直接赋值,赋值会改变内存内置,会使module.exports !== exports,这会导致内容失效