Home  >  Article  >  Web Front-end  >  Detailed explanation of 4 JavaScript concepts of Node.js

Detailed explanation of 4 JavaScript concepts of Node.js

黄舟
黄舟Original
2017-03-10 14:46:221487browse

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.

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);
});

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);

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');

4.回调函数

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

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

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

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

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

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

// output
hello
world


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:
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