node学习(2) -- 自定义模块(理解exports 和 module.exports的关系)
2018-02-08 14:48
591 查看
(一) 先了解一个简单的demo:
var a = {value: 1};
var b = a;
console.log(a); // {value: 1}
console.log(b); // {value: 1}
b.value = 2;
console.log(a); // {value: 2}
console.log(b); // {value: 2}
var b = {newValue: 3}
console.log(a); // {value: 2}
console.log(b); // {newValue: 3}
说明:如上,var b = a; b是a的引用,b和a指向同一块内存,所以当改变b.value的时候,内存中的value值被改变了,因此拿到的a也就变了, 而最后var b = {newValue: 3};当b被覆盖后,重新指向了一块内存,这时候a与b之间就没有什么关联了。
(二) 依据demo说明exports 和 module.exports的关系:
module.exports 初始值为一个空对象{};
exports 是指向module.exports的一个引用;
require() 返回的是module.exports而不是exports;
(三) 实例说明:
在另一个文件中:
因为require() 返回的是module.exports而不是exports;因此倘若 module.exports = 值;那么我们再通过exports添加的属性值就没什么作用了。
eg:
在另一个文件中:
var a = {value: 1};
var b = a;
console.log(a); // {value: 1}
console.log(b); // {value: 1}
b.value = 2;
console.log(a); // {value: 2}
console.log(b); // {value: 2}
var b = {newValue: 3}
console.log(a); // {value: 2}
console.log(b); // {newValue: 3}
说明:如上,var b = a; b是a的引用,b和a指向同一块内存,所以当改变b.value的时候,内存中的value值被改变了,因此拿到的a也就变了, 而最后var b = {newValue: 3};当b被覆盖后,重新指向了一块内存,这时候a与b之间就没有什么关联了。
(二) 依据demo说明exports 和 module.exports的关系:
module.exports 初始值为一个空对象{};
exports 是指向module.exports的一个引用;
require() 返回的是module.exports而不是exports;
(三) 实例说明:
// demo.js var x = '123'; var y = '456'; 方法一: module.exports.x = x; module.exports.y = y; 方法二: exports.x = x; exports.y = y; // 以上两种达到的目的是一样的
在另一个文件中:
var demo = require('./demo.js'); console.log(demo.x + ',' + demo.y); // 123,456
因为require() 返回的是module.exports而不是exports;因此倘若 module.exports = 值;那么我们再通过exports添加的属性值就没什么作用了。
eg:
// demo.js var x = '123'; var y = '456'; module.exports = 'ceshi'; exports.x = x; exports.y = y;
在另一个文件中:
var demo = require('./demo.js'); console.log(demo.x + ',' + demo.y); // undefined,undefined
相关文章推荐
- Node入门三:自定义模块、exports 和 module.exports
- nodeJS学习(9)--- nodeJS模块:exports vs module.exports
- node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理
- Node.js模块导出exports 和 module.exports 的区别
- node模块间传值(global、module.exports、exports)
- Node.js模块导出exports 和 module.exports 的区别
- Node.js中的模块接口module.exports
- 浅谈node中的exports与module.exports的关系
- Node.js的模块导出exports 和 module.exports 的区别
- [NODE之一]模块的exports和module.exports
- node.js学习笔记-模块module
- nodeJS实战:自定义模块与引入,不同模块的函数传递及回调处理,exports与module.exports(基于nodejs6.2.0)
- Node学习第五篇——模块module
- (译)Node.js的模块-exports和module.exports
- Node.js exports与module.exports的关系
- Node.js模块导出exports 和 module.exports 的区别
- Node.js模块导出exports 和 module.exports 的区别
- node.js 学习笔记之 module.exports与exports
- 理解 module.exports和node.js的exports
- node.js module初步理解,exports与module.exports的区别