本篇文章带大家了解一下Node.js中的全局对象,看看Node.js中有哪些全局对象,这些全局对象有什么用?怎么用?一起来学习吧!
所谓全局对象,就是可以直接访问的对象,比如
- 浏览器中的的全局对象就是
window
- Node 中的全局对象就是
global
下面让我们看看 Node 的全局对象具体有哪些? 这些对象又有什么用?【推荐学习:《nodejs 教程》】
如何获取全局对象
在某些老项目中,我们可能看到这样的代码片段
const getGlobalThis = () => { // 在 webworker 或 service worker 中 if (typeof self !== "undefined") return self; // 在浏览器中 if (typeof window !== "undefined") return window; // 在 Node.js 中 if (typeof global !== "undefined") return global; // 独立的 JavaScript shell if (typeof this !== "undefined") return this; throw new Error("Unable to locate global object"); }; const theGlobalThis = getGlobalThis(); if (typeof theGlobalThis.setTimeout !== "function") { // 此环境中没有 setTimeout 方法! }
这是因为各个 JS 环境获取全局对象的方式都是不同的,所以通过封装了一个getGlobalThis
来统一获取所有环境的全局对象
但是自从 ES13 特性出现后,支持使用globalThis
这种标准的方式来获取不同环境下的全局 this
对象(也就是全局对象自身)
if (typeof globalThis.setTimeout !== "function") { // 此环境中没有 setTimeout 方法! }
与浏览器相似的全局变量
Node.js 的全局变量与 Chrome 有一些差点,但也有很多类似的
我们启动一个简易的 Node 项目,然后打印如下的东西,看看能否正常输出
-
Date
对象 ✅
console.log(Date); // [Function: Date]
-
Math
对象 ✅
console.log(Math); // Object [Math] {}
-
setTimeout
对象 ✅
console.log(setTimeout); /* [Function: setTimeout] { [Symbol(nodejs.util.promisify.custom)]: [Function] } */
-
setInterval
对象 ✅
console.log(setInterval); // [Function: setInterval]
-
setImmediate
对象 ✅
console.log(setImmediate); /* [Function: setImmediate] { [Symbol(nodejs.util.promisify.custom)]: [Function] } */
-
requestAnimationFrame
对象 ❌
requestAnimationFrame
代表浏览器渲染的下一帧,所以在服务端环境是不存在的
// 浏览器渲染的下一帧,所以在服务端环境中是不存在的 console.log(requestAnimationFrame); // ReferenceError: requestAnimationFrame is not defined
Node.js 特有的全局变量
// 当前代码所运行的脚本位置 console.log(__filename); // D:\MyCode\Gitee\Learning.Node\geek-nodejs\08\index.js // 当前代码所运行的脚本目录 console.log(__dirname); // D:\MyCode\Gitee\Learning.Node\geek-nodejs\08
console.log(process);
version
: Node.js 版本号platform
, arch
: 运行环境的操作系统kill
, exit
: 用于管理,或者杀进程的操作hrtime
: 用于统计时间,可以精确到微秒级cpuUsage
: CPU 占用率resourceUsage
: 内存占用率env
: Node 的环境变量,作用:可以设置环境变量,以便在不同的开发中使用argv
:用户在启动程序时,敲击的命令是怎样的, 作用:命令行程序中使用
........................
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of What are the global objects in Node.js? What is the use?. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment