模块
- 一个js文件就可以是一个模块,每个模块中有独立的作用域。而被调用的时候node.js会把该模块包装成一个匿名函数,每个模块中的公共变量会变成当前匿名函数中的局部变量。
但是如果想对外暴露模块中的变量(如函数)
用法
模块hello.js1234hi(name){console.log('hello '+ name );}module.exports=hi; // 对外暴露函数变量调用模块的外部环境
12var hello=require('./hello'); //模块作为变量保存在当前作用域,相对路径hi(chellh); //调用模块中暴露的变量exports和module.exports
node.js为每个模块都会准备一个modules对象,123456789101112var module = {id: 'hello', //模块名exports: {}};var load = function (module) {// hello.js的文件内容...// load函数返回:return module.exports;};var exported = load(module.exports, module);save(module, exported);当我们暴露函数变量的时候
module.exports=hi;
,函数变量hi实际是module对象中的exports的一个值,module再作为参数传递给函数load,即真正作用的是module对象。12exports.foo = function () { return 'foo'; };module.exports.foo = function () { return 'foo'; };其中,exports是指向module.exports的一个引用。exports 和 module.exports是指向同一块内存块,如果直接给exports赋值,则会改变exports的指向,而不会影响到module.exports,但传递给load函数的是modul对象。
12module.exports = function () { return 'foo'; }; //正确exports = function () { return 'foo'; }; //错误,改变exports的指向
Event Loop
看这里js的单线程和异步