[Nodejs]Nodejs基础学习(二)-模块机制

补充:

关于Nodejs本身

Nodejs不是一门语言、框架或者类库,他是一种运行时环境,

它一个很大的贡献就是,使得JS代码的解释和执行从浏览器脱离,

使用了V8引擎(代码执行效率很高),

为JS带来了一些服务器特性,

使用npm开源库生态系统进行包管理。

模块机制

参考资料

模块机制的引出

Nodejs遵循的是CommonJS规范,其核心要求是通过require来加载其他依赖的模块。

每一个文件都是一个模块,拥有自己独立的作用域,变量,以及方法等,对其他的模块都不可见。在模块内部,我们熟悉的module变量(对象)就代表当前模块,其exports属性即为对外暴露的接口。

exportsmodule.exports的区别

module是由模块系统生成的,编写模块时,要对外声明模块接口,module提供了对外暴露接口的方法,并决定暴露什么内容,使用require加载一个模块时,实际加载的是该模块指定的module.exports

module.exports 初始值为一个空对象 {},exports 是指向的 module.exports 的引用

模块导出的时候,真正导出的执行是module.exports,而不是exports,

当module.exports改变时,exports与module.exports的引用断开。(一般最后要使用exports = module.exports,令exports 重新指向 module.exports,以保证exports特性正常使用)

两者的区别在于:

  • exports返回模块的一个函数,可以直接调用(对外暴露调用该模块的人能够使用哪些函数)XXXXX
  • modules返回一个类,需要创建对象再调用(对外暴露该对象或类)XXXX
  • require() 返回的是 module.exports 而不是 exports

注意

  • 如果直接给exports赋值,则exports对module.exports的引用就会被转移,导入接口会失效。
  • exports一般用来辅助module.exports添加函数,但一般只用module.exports,而不用exports

require()

返回对应模块暴露的module.exports

用于加载和调用其他文件导出模块的方法,

换句话说,引入的任何一个模块都对应一个Module实例,即使是入口文件也是如此。

模块创建和导入示例

模块创建、导出
console.log(module.exports === exports);
// 1.直接对外暴露的接口,是一个类,而非单纯的方法,调用方法其需要实例化
// 需要注意的是,此时module.exports重新指定了引用,已经和exports不同
module.exports = function(name, age) {
    this.name = name;
    this.introduce = function() {
        return this.name +' is one of the members of huihe';
    };
};
console.log(module.exports === exports);
// 2.一个可以直接调用的函数,不需要实例化可以直接调用
// 将single函数以方法形式暴露在模块外,名字不必与原本相同
// console.log(module.exports === exports);
module.exports.who = function a() {
    console.log("这是一个单独的函数1");
}

// 3.此时使用exports添加,会发现无法调用,这是因为exports和module.exports引用已经不相同
exports.what = function b() {
    console.log("这是一个单独的函数2");
}
console.log(module.exports)

// 4.exports重新指向module.exports
exports = module.exports
// 此时使用exports添加,可以正常添加,因为重新建立了连接
exports.what = function b() {
    console.log("这是一个单独的函数2");
}
console.log(module.exports)

导出模块的内部测试

请添加图片描述

导入、使用
var ObjectHuihe = require('./huihe.js');


// module.exports返回的是类,要先将其实例化为对象,才能进行调用。
huihe = new ObjectHuihe('aaa');
console.log(huihe.introduce());
console.log(huihe.name);
//暴露的是可以直接调用的方法,直接使用引入的类进行调用即可,不要遗漏括号。
console.log(ObjectHuihe.who());
// 直接调用模块对象,返回的是一个匿名函数,包含了直接向module.exports添加的函数
console.log(ObjectHuihe);
console.log(ObjectHuihe.what());

请添加图片描述

顺带输出undefine不太明白为什么。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值