Node.js中module.exports和exports的区

2017-05-06  本文已影响0人  杨慧莉

引用类型和基本类型

在说明module.exports和exports的区别之前,先来介绍一个概念:
ECMAScript的变量值类型共有两种:

先来看如下代码:

let a = {key: 1};
let b = a;

console.log(a);
console.log(b);

b.key = 2;
console.log(a);
console.log(b);

b = {key: 3};
console.log(a);
console.log(b);

运行结果为:

{ key: 1 }
{ key: 1 }
{ key: 2 }
{ key: 2 }
{ key: 2 }
{ key: 3 }

说明:

module.exports 和 exports 的区别

module.exports和exports属于Object类型,属于引用类型
区别可概括为以下几点:

module.exports和exports之间的关系可以用以下代码模仿:

const module = { exports: {}};
let exports = module.exports;
exports.a = 1;
console.log(module.exports); // {a: 1}

exports = {b:2};
console.log(module.exports); // {a: 1}```
说明:
- exports 和 modules.exports 引用的是同一个对象
- 如果我们给 exports 增加属性,那么因为 modules.exports 也会增加相同的属性,此时 modules.exports === exports
- 如果对 exports 赋值的话,那么就会造成 modules.exports 和 exports 不指向同一个对象,此时再对 exports 做任何动作都跟 modules.exports 没有任何关系了
- **如果想要在模块文件中提供其他模块可以访问的接口,就要避免对exports赋值**

####module.exports和exports用法示例:
- **exports用法**

//1.js

function sum(a,b) {
let count=a+b;
return count;
}
exports.a=sum;

//2.js
let Sum=require('./1.js');

function main() {
console.log(Sum.a(1,2));
}
main(); //输出结果为3

- **module.exports用法**

//1.js
function sum(a, b) {
return a+b;
}

function multiply(a,b) {
return a*b;
}

module.exports = {
a: sum,
b: multiply
};

//2.js
const Sum=require('./1.js');

function main() {
console.log(Sum.a(1,2)); //输出3
console.log(Sum.b(2,10)); //输出20
}
main();

- **module.exports的对象、prototype、构造函数使用**

// 4.js

const a = require('./5.js');
// 若传的是类,new一个对象
let person = new a('Kylin',20);
console.log(person.speak());
// my name is Kylin ,my age is 20

// 若不需要在构造函数时初始化参数,直接调用方法/属性// a.speak();
// my name is kylin ,my age is 20


// 5.js
// Person类
function Person(name,age){
this.name = name;
this.age = age;
}

// 为类添加方法
Person.prototype.speak = function(){
console.log('my name is '+this.name+' ,my age is '+this.age);};
// 返回类
module.exports = Person;

// 若构造函数没有传入参数(name,age),直接传入对象
// module.exports = new Person('kylin',20);

**注意:**
- 如果只是单一属性或方法的话,就使用exports.属性/方法。要是导出多个属性或方法或使用对象构造方法,结合prototype等,就建议使用module.exports = {}
- 对 module.exports 的赋值必须立即完成, 不能在任何回调中完成

**参考资料:**
https://segmentfault.com/a/1190000007403134
https://cnodejs.org/topic/52308842101e574521c16e06
https://segmentfault.com/a/1190000004157460
https://www.zhihu.com/question/26621212
https://www.ycjcl.cc/2017/02/10/module-exportshe-exportsde-qu-bie/
上一篇下一篇

猜你喜欢

热点阅读