nodejs-global

global


在node中有一个全局变量 global, 它的作用和网页中window类似。

在全局中创建的变量都会作为global的属性保存。

在全局中创建的函数都会作为global的方法保存。

console.log(global);

打印全局变量global

Node中全局对象下有以下方法,可以在任何地方使用,global可以省略。

console.log() 在控制台中输出

setTimeout() 设置超时定时器

clearTimeout() 清除超时时定时器

setInterval() 设置间歇定时器

clearInterval() 清除间歇定时器

global的详细解释:

Node.js 全局(global)_w3cschool


模块作用域

默认在 Node 中,每一个 JS 文件中定义的 方法、变量,都是属于 模块作用域的.


当node在执行模块中的代码时,他会首先在代码的最顶部并添加如下代码:

模拟模块作用域

实际上模块中的代码都是包装在一个函数中执行的,并且在函数执行时,同时传递进了5个实参

exports 该对象用来将变量或函数暴露到外部

查看exports:

查看方式: console.log(arguments);

require 函数,用来引入外部模块

查看require:

查看方法:arguments.callee

module 代表的是当前模块本身

查看module:

查看方法 console.log(arguments.callee+"module'');

 exports就是module的属性

既可以使用 exports 导出,也可以使用module.exports 导出

判断exports是否是module的属性

__filename 当前模块的完整路径

查看_filenname:

查看方法: console.log(__filename);

__dirname 当前模块所在文件夹的完整路径

查看__dirname :

console.log(__dirname);

对dirname和filename的详解:

node的内置常量__dirname和__filename_北芒的博客-CSDN博客_node 常量


exports和module.exports

exports 实际指向 module.exports。

在拼接之后的代码中,给这个函数传入的 exports 是 module.exports, 也就是说 exports 和 modules.exports 引用的是同一个对象。 如果我们给 exports 增加属性,那么因为 modules.exports 也会增加相同的属性,此时:

modules.exports === exports。

通过exports只能使用.的方式来向外暴露内部变量

exports.xxx = xxx


而module.exports既可以通过.的形式,也可以直接赋值

module.exports.xxx = xxx

module.exports = {}



exports指向module.exports

如果module.exports等于对象,返回false

此时exports不指向 module.exports

除非再将module.exports指向exports

重新等于true

对 exports和module.exports指向的详解:

module.exports、exports模块化导入导出方式 - cc_loving - 博客园 (cnblogs.com)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容