Four JavaScript concepts that Node. js developers must be familiar

Source: Internet
Author: User

Four JavaScript concepts that Node. js developers must be familiar
Four JavaScript concepts that Node. js developers must be familiar

Node. js is a server-side development framework built based on Google Chrome's V8 JavaScript Engine. Although Node. js itself is developed using C ++, it uses JavaScript as its application language.
Node. js has four concepts that are very important to beginners and should be understood and mastered. As follows:

1. Non-blocking or asynchronous I/O

Because Node. js is a server-side framework, one of its main tasks is to process requests from browsers. In traditional I/O systems, new requests can be sent only after the response of previous requests is returned. That is why I/O communication is blocked. The server blocks the next incoming request, and then processes the current request until the request processing is complete, sends a response, and then removes the blocking of the next incoming request.

Node. js does not follow the above blocking I/O communication principles. If a request requires a long processing time, Node. js sends the request to the event loop and processes the next request on the call stack. Once the request in the event loop is processed, it will notify Node. js, and Node. js will return a response to the browser. The following is an example:

1. Blocking I/O
// Table 1, obtain order 1var order1 = orderBlocking (['coke', 'iced Tea ']); // Service Order 1 serveOrder (order1 ); // once the order service is completed, the waiter goes to another table // table 2, order 2var order2 = orderBlocking (['coke', 'water']); // service order 2 serveOrder (order2); // once the order service is completed, the waiter goes to another table // table 3, order 3var order3 = orderBlocking (['iced Tea ', 'water']); // Service Order 3 serveOrder (order3); // once the order service is completed, the waiter goes to another table

In the above example, the waiter obtains the order at the first table and then provides the service to the order. After the service is completed, the waiter immediately moves to the next table to obtain the order. Orders are processed in chronological order. servers only serve orders and block other orders.

2. Non-blocking I/O
// Take the order delivered at table 1 and move it to the next table orderNonBlocking (['coke', 'iced Tea '], function (drinks) {return serveOrder (drinks );}); // take the order delivered at table 2 and move it to the next table orderNonBlocking (['beer', 'whiskey'], function (drinks) {return serveOrder (drinks );}); // take the order delivered at table 3 and move it to the next table orderNonBlocking (['hambler', 'pizza'], function (food) {return serveOrder (food );});

In the preceding example, the waiter obtains the order and notifies the cook to go to the next table. When the first order is processed, the waiter moves to the next table to obtain the order. The waiter does not block the order.

Ii. Prototype

In JavaScript, Prototype is a complex concept. Node. js uses many prototype fields, so every JavaScript developer should be familiar with this concept.

Programming languages such as Java and C ++ all implement typical inheritance, which facilitates code reuse. First, construct a base class (as the blueprint of the object), and then create an object or extend the class from this class.

However, JavaScript language does not have such a concept. First, create an object in JavaScript, and then expand this object or create a new object from this object. This is the so-called prototype inheritance, which is implemented through prototype.

Each JavaScript Object is linked to a prototype object and can inherit its attributes from the prototype object. Prototype is similar to classes in object-oriented languages, but they are actually different. They are all objects. Each Object is linked to Object. prototype, which is a predefined JavaScript Object.

If you are using obj. when propName or obj ['propname'] is used to view attributes, does this object have such attributes? You can use obj. hasOwnProperty ('propname') to check whether this property exists in the prototype object during JavaScript runtime. If the prototype object does not have such an attribute, check whether the object has such an attribute in sequence (it is possible that the object inherits several levels) until the property is matched. If the entire property chain does not have such an attribute, the undefined value is returned.

Here is an example:

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

When creating a new object, you can select the prototype of the object. In the above Code, we added the create method of an Object function. The create method creates a new object, uses another object as its prototype, and passes it as a parameter to the new object.

When we modify a new object, its prototype remains unchanged and will not be affected. However, if we want to modify a prototype object, it will affect all objects based on this prototype object.

Prototype is a complex concept and needs to be further explored.

Iii. Modules

If you are familiar with the concept of Package in Java, you will understand the concept of Node. js modules. There is no difference between the two. A module is a simple JavaScript file that contains code for a specific purpose. Module Pattern is used to simplify Code Organization and navigation. To use the attributes of a module, you must import require in JavaScript, which is the same as import in Java.

Node. js has two types of modules:

1. Core Module)

The core module contains the library pre-compiled to Node. js. The template of the core module provides developers with frequently-occurring and repetitive code snippets. Without these fragments, developers will be stuck in these repetitive and tedious tasks. Common core modules include the HTTP module, URL module, EVENTS module, and file system module.

2. User-Defined Module)

User-defined modules are implemented by developers for specific functions. It is usually developed when the core module cannot meet the required functions. User-defined modules also need to be imported using require. If it is a core module, you only need to input the module name for require import. for user-defined modules, the path of the file system needs to be imported for require import.

For example:

// Import the core module var http = require ('HTTP); // import the User-Defined module var something = require ('. /folder1/folder2/folder3/something. js ');
Iv. Callback

In JavaScript, a function is considered to be the first-level object. This means that developers can perform all operations as common objects. You can assign a function to a variable, pass a function as a parameter to a method, or use a function as an object attribute, or even return a function from a function.

Callback is an anonymous function in JavaScript. It can be passed as a parameter to another function. You can also execute a callback function or return a callback function in subsequent function execution. This is a widely used programming paradigm for callback functions.

When passing a callback function as a parameter to another function, we only need to pass the function definition, that is, we do not need to know when the callback function will be executed. This depends entirely on the function calling mechanism, so it is named after the callback. Callback functions are the basis for non-blocking communication and asynchronous processing of Node. js.

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

This is one of the simplest callback functions. We pass the anonymous function as a parameter to the setTimeout function, while the anonymous function only outputs the log "world" on the console ". Since this is just a function definition, we do not know when it will be executed. Execution depends on the output of the setTimeout Function after 2000 milliseconds.

Therefore, the second log statement outputs "hello" on the console, and then outputs the "world" log defined by the callback function after two seconds ".

// outputhelloworld

Understanding the above four concepts can help you gain insight into Node. js.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.