node.js学习之module调用方式

1.创建并测试模块

创建模块的时候可以两种方式
一, function hello() {
console.log('Hello');
}

function world() {
console.log('World');
}
exports.hello = hello;
exports.world = world;
//相当于exports对象中添加函数,作为模块被其他调用,并且对象.函数名();调用

--------
var hello = require('./mymodule');
// 也可以写作 var hello = require('./mymodule.js');

// 现在就可以使用mymodule.js中的函数了
hello.hello(); // >> Hello
hello.world(); // >> World
//在当前文件夹shift按下后打开命令框 node index.js直接执行


二, function Hello() {
this.hello = function() {
console.log('Hello');
};

this.world = function() {
console.log('World');
};
}

module.exports = Hello;
-----------
var Hello = require('./mymodule');
var hello = new Hello();
//模块中是构造函数,可以被new成对象的方式进行调用,所以就new下
hello.hello(); // >> Hello
hello.world(); // >> World

2. module.exports和exports 问题详细理解

exports是引用 module.exports的值。module.exports 被改变的时候,
exports不会被改变,而模块导出的时候,真正导出的执行是
module.exports,而不是exports
exports在module.exports 被改变后,失效。

module 是一个对象,每个模块中都有一个 module 对象, module 是当前模块的一个引用。 module.exports 对象是Module系统创建的,而 exports 可以看作是对 module.exports 对象的一个引用。在模块中 require 另一个模块时,以 module.exports 的值为准,因为有的情况下, module.exports exports 它们的值是不同的。 module.exports exports 的关系可以表示成这样:
// module.exports和exports相同的情况var m = {};
// 表示 modulevar e = m.e = {}; // e 表示 exports, m.e 表示 module.exportsm.e.a = 5;e.b = 6;console.log(m.e);
// Object { a: 5, b: 6 }console.log(e); // Object { a: 5, b: 6 }

// module.exports和exports不同的情况var m = {};
// 表示 modulevar e = m.e = {};
// e 表示 exports, m.e 表示 module.exportsm.e = { c: 9 };
// m.e(module.exports)引用的对象被改了e.d = 10;console.log(m.e);
// Object { c: 9 }console.log(e); // Object { d: 10 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值