门户类网站注重什么,商城网站要怎样建设,外链吧怎么使用,在上阿里云做网站一、介绍
1.1 什么是模块化与模块 ?
将一个复杂的程序文件依据一定规则#xff08;规范#xff09;拆分成多个文件的过程称之为 模块化
其中拆分出的 每个文件就是一个模块 #xff0c;模块的内部数据是私有的#xff0c;不过模块可以暴露内部数据以便其他 模块使用
1…一、介绍
1.1 什么是模块化与模块 ?
将一个复杂的程序文件依据一定规则规范拆分成多个文件的过程称之为 模块化
其中拆分出的 每个文件就是一个模块 模块的内部数据是私有的不过模块可以暴露内部数据以便其他 模块使用
1.2 什么是模块化项目 ?
编码时是按照模块一个一个编码的整个项目就是一个模块化的项目
1.3 模块化好处
下面是模块化的一些好处
1. 防止命名冲突
2. 高复用性
3. 高维护性
1.4模块化使用
导出数据方式一
exports.num num;
exports.sum sum;
exports.Animal Animal;
导出数据方式二
// 通过module.exports 等于一个对象来导出数据
// 对象可采用es6简化对象的写法
module.exports {num,sum,Animal
};
导入数据
// 注意1 如果要使用某个模块里面的数据则需要使用 require 关键字进行导入。
// 注意2在导入用户自己开发的模块的时候需要加上路径1. 相对路径多 2. 绝对路径 注意: ./ 必须写上
// 注意3模块文件的扩展名(后缀名)可以写也可以不写
// 注意4导出的模块一般需要使用一个变量来接收一般把接收的量定义为常量
// 注意5: 定义常量的名称和文件的名称保持一致这个不是必须大家都这么做
const m1 require(./modules/m1.js);
完整代码
// m1.js中
let num 10;
function sum(a, b) {return ab
}class Animal{constructor(){this.age0}
}// 导出数据方式1
// exports.num num;
// exports.sum sum;
// exports.Animal Animal;// 导出数据方式2
// 通过module.exports 等于一个对象来导出数据
// 对象可采用es6简化对象的写法
module.exports {num,sum,Animal
};
模块的使用
//01-模块的使用.js
const m1 require(./modules/m1.js);console.log(m1); //{ num: 10, sum: [Function: sum], Animal: [Function: Animal] }
console.log(m1.sum(10, 20));
const obj new m1.Animal(); //30
console.log(obj.age); //0
二、模块里面this的指向问题
exports实际上是module.exports的引用
在 nodejs 里面的 this 代表当前的这个模块也就是 exports 对象
console.log(exports); //{}
console.log(module.exports); //{}
console.log(exports module.exports); //true exports实际上是module.exports的引用console.log(this, this); // this {}console.log(this exports);// true // 在 nodejs 里面的 this 代表当前的这个模块也就是 exports 对象 并且交互模式下没有exports这个对象
console.log(global this ); //false this不指向全局对象 三、CommonJS 规范
module.exports 、 exports以及require 这些都是CommonJS模块化规范中的内容。 而 Node.js 是实现了 CommonJS 模块化规范二者关系有点像 JavaScript 与 ECMAScript
CommonJS 规定 ① 每个模块内部module 变量代表当前模块。 ② module 变量是一个对象它的 exports 属性即 module.exports是对外的接口。 ③ 加载某个模块其实是加载该模块的 module.exports 属性。require() 方法用于加载模块。