commonjs定义
每个文件就一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见。
1.私有作用域不会污染全局作用域。
2.模块可加载多次,只会在第一次加载时运行一次,然后结果会被缓存起来,
以后在使用,就直接读取缓存结果。想要让模块再次运行,必须清除缓存
3.模块加载顺序是按照其在代码中出现的顺序
快速上手
1、require()用来引入外部模块,
2、exports()用来导出当前模块的变量和方法,
3、module对象代表模块对象
单变量方法导出引入
// a.js 导出
function add(a, b) {
return a + b;
}
module.exports = add;
// b.js 引入
const add = require('./a.js');
console.log(add(10, 20));
多方法变量导出引入
// a.js 导出
function add(a, b) {
return a + b;
}
function mul(a, b) {
return a * b;
}
module.exports = {
add,
mul
};
// b.js 引入
const { add, mul } = require('./a.js');
console.log(add(10, 20));
console.log(mul(10, 20));
补充说明:
//const { add, mul } = require('./a.js');
const opt = require('./a.js');
const add = opt.add
const mul = opt.mul
和上面的注释是等价的,这就是解构的语法.
对象解构
let node = {
type : 'identifier',
name : 'foo'
};
let {type,name} = node;
console.log(type);//'identifier'
console.log(name);//'foo'
网友评论