您的位置:首页 > Web前端 > Node.js

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;

(三) 实例说明:

// 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息