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 }