Table of Contents
1. Non-blocking or asynchronous I/O
2. Prototype
3. Modules
4.回调函数
Home Web Front-end JS Tutorial Detailed explanation of 4 JavaScript concepts of Node.js

Detailed explanation of 4 JavaScript concepts of Node.js

Mar 10, 2017 pm 02:46 PM

Detailed explanation of 4 JavaScript concepts in Node.js

Wouldn’t it be amazing if you only need to know one programming language to build a full-stack application? To make this idea a reality, Ryan Dahl created node.js. Node.js is a server-side framework built on Chrome's powerful V8 JavaScript engine. Although originally written in C++, the application runs through JavaScript.

In this way, the problem is solved. One language can rule them all. Moreover, you only need to use this one language throughout the entire application. Therefore, we need to have a deep understanding of node.js. That's what this article is about.

The following four basic concepts are necessary if you want to master node.js. I will introduce them to you in as short a story as possible.

1. Non-blocking or asynchronous I/O

Since Node.js is a server-side framework, one of its main jobs is to handle browsing server request. In a traditional I/O system, the current request is not issued until the response (HTML page) from the previous request has arrived. That's why it's called blocking I/O. The server blocks other requests in order to process the current request, which causes the browser to wait.

Node.js does not follow this principle of I/O. If a request takes a long time, Node.js will send the request to the event loop and continue processing the next request in the call stack. Once the pending request has finished processing, it tells Node.js and the response is rendered on the browser.

Use a fictitious example to understand this:

Blocking I/O

// take order for table 1 and wait...
var order1 = orderBlocking(['Coke', 'Iced Tea']);
// once order is ready, take order back to table.
serveOrder(order1);
// once order is delivered, move on to another table.
// take order for table 2 and wait...
var order2 = orderBlocking(['Coke', 'Water']);
// once order is ready, take order back to table.
serveOrder(order2);
// once order is delivered, move on to another table.
// take order for table 3 and wait...
var order3 = orderBlocking(['Iced Tea', 'Water']);
// once order is ready, take order back to table.
serveOrder(order3);
// once order is delivered, move on to another table.
Copy after login

In this restaurant example, the waiter gives the menu, waits for the order to be completed, and then Return to the table and serve according to the menu. While the current customer is ordering, the waiter is waiting nearby and does not accept menus from other customers.

Non-blocking I/O

// take order for table 1 and move on...
orderNonBlocking(['Coke', 'Iced Tea'], function(drinks){
  return serveOrder(drinks);
});
// take order for table 2 and move on...
orderNonBlocking(['Beer', 'Whiskey'], function(drinks){
  return serveOrder(drinks);
});
// take order for table 3 and move on...
orderNonBlocking(['Hamburger', 'Pizza'], function(food){
  return serveOrder(food);
});
Copy after login

In this example, the waiter gets the menu, informs the chef, and then returns to get another menu. In the process of completing the first menu, he not only serves the current customers in order, but also accepts orders from other customers. Waiters don't waste time by blocking orders from other customers.

2. Prototype

Prototype is a complex concept in JavaScript. But because you use prototypes many times in Node.js, every JavaScript developer must understand this concept.

In languages ​​that implement classical inheritance, such as Java, or C++, for languages ​​with code reuse in mind, you first have to write a class and then create objects from that class or extend that class. However, the concept of classes does not exist in JavaScript. First create an object in JavaScript, then add your own objects from this object, or create new objects. This is called archetypal inheritance and realization through archetypes.

Every JavaScript object is linked to a prototype object from which it can inherit properties. Prototypes are similar to classes in other OO languages, but the difference is that they are also objects themselves. Every object is linked to Object.prototype, and Object.prototype comes with JavaScript predefined.

If you look up a property via obj.propName or obj['propName'] and the object does not have a property that can be checked via obj.hasOwnProperty('propName'), then the JavaScript runtime will Find properties in prototype objects. If the prototype object does not have such a property, then its prototypes are checked in sequence until a match is found, or Object.prototype is reached. If no prototype chain exists for the property, it results in an undefined value.

Understand this concept with the following sample code:

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        var F = function () {};
        F.prototype = o;
        return new F();
    };
var otherPerson = Object.create(person);
Copy after login

When you create a new object, you must choose an object that should be its prototype. Here, we add a method to the Object function. This method creates a new object using another object as its prototype, which is passed to it as a parameter.

When we change a new object, its prototype is not affected. However, when we make changes to a prototype object, these changes are visible to all objects based on that prototype.

Prototype is a complex concept. I will elaborate on this in another article.

3. Modules

If you have ever been exposed to packages in Java, modules in Node.js are no different. If not, then don’t worry. Modules are simple JavaScript files that contain code for a specific purpose. The module pattern is used to make your code easy to navigate and use. To use a module attribute, you need to require it in a JavaScript file, much like importing a package in a Java class.

There are two types of modules in node.js.

Core Modules - These modules are pre-compiled with the Node.js library. The purpose of core modules is to provide developers with frequently occurring and repetitive code snippets that, if unavailable, would put developers in the position of having to write the same code over and over again. Some common core modules are HTTP, URL, EVENTS, FILE SYSTEM, etc.

用户定义模块——用户定义模块是开发人员在应用程序内创建用于特定目的的模块。当核心模块不能满足期望功能的时候就需要用户定义模块。

模块通过require函数提取。如果它是一个核心模块,那么参数仅仅是模块的名称。如果它是一个用户自定义模块,那么参数就是该模块在文件系统中的路径。例如:

// extract a core module like this
var http = require('http);
// extract a user defined module like this
var something = require('./folder1/folder2/folder3/something.js');
Copy after login

4.回调函数

在JavaScript中,函数被认为是第一类对象。这意味着你可以对这些函数做所有可对常规对象做的操作。你可以赋值函数给变量,作为参数传递函数给方法,作为对象属性声明函数,甚至从函数返回函数。

回调函数是JavaScript中的匿名函数,它可以作为参数传递给其他函数,要么被执行或返回自函数稍后执行。这是回调函数——这个使用最广的函数编程范式的基础。

当我们将回调函数作为参数传递给另一个函数的时候,我们只能传递函数定义……换言之就是,我们不知道这个回调函数什么时候会执行。这完全取决于调用函数的机制。它会在以后的某个时间点“回调”,因此而得名。这也是非阻塞或Node.js异步行为的唯一基础,如下例所示。

setTimeout(function() {
    console.log("world");
}, 2000)
console.log("hello");
Copy after login

这是回调函数最简单的例子之一。我们将一个匿名函数作为一个参数传递,这个参数只需在控制台上记录一些输出到setTimeout函数。它是唯一的函数定义,但是不知道何时执行。这需要经过2秒后,通过第二个参数,调用setTimeout函数来决定。

首先,第二个日志语句记录输出到控制台,然后,2秒钟后,回调函数中的日志语句记录输出。

// output
hello
world
Copy after login


The above is the detailed content of Detailed explanation of 4 JavaScript concepts of Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles