Node.js(自定义模块)
Common.js规范(Nodejs)中自定义模块的规定:
require谁就会运行谁
在nodejs中,可以在js文件中require(导入)另一个js文件,此时就会立即运行那个引用的js文件。
js文件在Node.js 中天生作用域隔离
js文件在Node.js中天生作用域隔离的!
为什么?
因为没有了window对象。
使用exports.** = **的语法进行暴露(导出)
-app.js
-a.js
a.js文件中定义了m值,并进行了暴露
var m = 100;
exports.m = m;
在app.js文件中:
var a = require("./a.js");
console.log(a.m);
需要注意的是两点:
① 建议: 暴露的时候必须是exports.** = ** , **必须一致。
② 建议: 接受的时候,文件名是什么,就用什么接收。
// 正确的:
var a = require("./a.js");
console.log(a.m);
nodejs在运行的时候,接受的那个变量(a)会自动成为exports对象。
模块内部可以使用exports对象进行成员导出, 使用require方法导入其他模块。
exports. = 的写法天生有namespace(命名空间)
-app.js
-yuan.js
-juxing.js
yuan.js和juxing.js文件里面都定义了mianji和zhouchang函数,但是引入的时候由有命名空间,所以不乱套。
var yuan = require("./yuan.js");
var juxing = require("./juxing.js");
console.log(yuan.mianji(15));
console.log(yuan.zhouchang(15));
console.log(juxing.mianji(10,12));
console.log(juxing.zhouchang(10,12));
使用module.exports=**暴露(导出)
当一个js文件中仅仅希望暴露一个东西(通常是构造函数),此时我们可以使用module.exports = **的方法暴露。
-app.js
-people.js
// People.js:
function People(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.sayHello = function(){
console.log("你好我是" + this.name);
}
module.exports = People;
// app.js:
var People = require("./People.js");
var xiaoming = new People("小明" , 12 , "男");
xiaoming.sayHello();
// 如果仍然使用exports.People = People的方法暴露,此时就势必要:
var xiaoming = new People.People("小明" , 12 , "男");
总结一下:
● 如果一个js文件中有多个东西要暴露(通常是暴露一些相关的函数比如面积、周长),此时用:
exports. = ;
exports. = ;
暴露。
● 如果一个js文件中只暴露一个文件(通常是构造函数),此时用:
module.exports = **;
暴露。
//导出的方式:
// 1. module.exports : 接收一个对象,对象中包含多个需要导出的内容,(数量不限)
// 建议: 按需导出
module.exports = {
a,
Person
}
//2. exports : module.exports的引用, 导出单个目标时,使用
// exports.a = a;
// exports.Person = Person;
exports是module.exports的别名(地址引用关系),导出对象最终以module.exports为准
// 导入方式1 使用变量来保存接收到的数据
// let index = require("./index.js");
// console.log(index);
// console.log("我是被导入的" + index.a);
// let p = new index.Person();
// p.hobby();
// 导入方式2 直接使用解构赋值 推荐方式
let {a,Person} = require("./index");
console.log("我是被导入的" + a);
let p = new Person();
p.hobby();
// 上述导入方式,实际是一种导入,有不同的接收方式