node学习(2) -- 自定义模块(理解exports 和 module.exports的关系)

(一) 先了解一个简单的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的关系:

  1. module.exports 初始值为一个空对象{};
  2. exports 是指向module.exports的一个引用;
  3. 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值