Node. js-js tutorial

Source: Internet
Author: User
This series of tutorials teach you how to use Node. js to develop applications, and will teach you all the "advanced" JavaScript knowledge you need. It is never a "HelloWorld" tutorial. I will share with you the first article about NodeJS-common Javascript knowledge and how to transition from Javascript developers to NodeJS developers (I will not introduce specific frameworks ). Before reading this article, I hope you have some preliminary knowledge about javascript.

Javascript is an interpreted language for prototype models. The explanatory model will be discussed in later NodeJS. prototype chain is one of the Javascript object-oriented implementation methods before ES6, and a new implementation method is added to the class supported in ES6. Everything in Javascript is an object, including a "class ". Those who have been familiar with ruby/python metaprogramming may feel familiar with this. Javascript is also easy to implement dynamic generation class methods.

1. Simple "class" implemented based on prototype chain"

var Person = function(name){ this.name = name;};Person.staticSay = function(name){ console.log('Hello ' + name);};Person.prototype.sayHi = function(){ Person.staticSay(this.name);}

Some common standards are introduced. For example, all the methods in Javascript are named by camper, single quotes and two spaces are preferred. For more standards, refer to https://github.com/airbnb/javascript.

StaticSay in the Code is a static method, that is, it can only be called by Person. staticSay. When the above Person generates an instance, such as var vincent = new Person ('Vincent ');, vincent will automatically inherit the Person. all prototype methods (this in the Code refers to the current context, that is, vincent in the previous section ).

You can also dynamically add methods for the object vincent, such as the following code:

var vincent = new Person('vincent')vincent.tellName = function(){ console.log('Hi, i\'m am' + this.name)};

Then, when you need to simulate inheritance, you need to work on prototype. For example, the following example uses Worker. prototype = new Person (). All methods and attributes of the instance object returned by new Person () are assigned to prototype, simulating inheritance in disguise. In this way, the content in prototype is eventually searched layer by layer (because each instance has methods in prototype until the Object is retrieved ). Of course, prototype can also be assigned through traversal to simulate inheritance.

2. Context switching

The most intuitive manifestation of context is this in the code block, which is usually used in Object-Oriented Programming to refer to the corresponding instances generated by the current "class", consistent with self in other languages.

Using the example above, we have implemented a Person. prototype. sayHi method. Now I have a new object, and the code is as follows:

var Cat = function(name){ this.name = name;}var c = new Cat('tomcat');

If one day the cat was suddenly whimsical and wanted to introduce him as a human, he would not use the sayHi method. However, you can use console. log (Person. prototype. sayHi) to obtain the human sayHi method. How can cats use it?

Javascript has two methods: call and apply. The difference between them is that the parameters are different (Google) and the function is to switch context. Simply put, this in the Person. prototype. sayHi function can be converted into other objects. Usage: Person. prototype. sayHi. call (c ).

Is this practical? For example:

var doSomething = function(){ var persons = arguments;};

In the above function, all parameters are obtained through the keyword arguments to support an indefinite number of parameters. Now we want to use some methods of the original Array type for persons. How can we implement this? Context switching can be implemented here:

Var doSomething = function () {var persons = arguments; // use the slice Method of Array to convert the arguments object to Array instance var persons_arr = Array. prototype. slice. call (arguments );};

3. Closure

Common Code

for (var i = 0; i < 3; i ++){ setTimeout(function(){  console.log(i); }, i)}

What results will this output? 0 1 2? The actual situation is that when setTimeout executes the callback for the first time, the for loop has ended. That is to say, at this time, I is already 3, and the final output result is 3 3.

When you need to protect a variable so that it is not affected by peripheral code, you may need to consider the closure-a block of closed scopes.

for (var i = 0; i < 3; i ++){ +function(i){  setTimeout(function(){   console.log(i);  }, i) }(i)}

Why is there another method to implement the scheme and +? please google it on your own. The I scope in the closure is a closed scope, so the I in the closure is not changed by the execution outside, so 0 1 2 can be successfully output.

This section briefly introduces some javascript features, such as the prototype chain of keywords, call, apply, and arguments keywords. For more suggestions, refer to books such as the authoritative guide, or you can quickly understand the basic types and methods of each type. There are some amazing code, such as getting the string of the current code and then processing it to get what you want, use getter and setter to perform special operations when you obtain or assign values to object attributes.

4. Differences between NodeJS and Javascript development

This section describes the basic knowledge of require loading. First, we will introduce some code:

//. Jsmodule. exports = {name: "a", doSomething: function () {return "something" ;}// B. jsvar a = require ('. /A') global. a_name =. name; // c. jsrequire ('. /B '); console. log (a_name) // print a after execution

What happens when we execute node c. js?

Require is the nodes keyword. Although NodeJS is famous for its Asynchronization, its require is blocked. Otherwise, other modules are not loaded and the following code has been executed.

Require. the resolve () method is used to find the actual path of the file you reference. check whether there is a cache in the cache. Otherwise, the file will be read and parsed. Therefore, the Code executed in a js file will only be executed when it is require for the first time. (Tip. require. cache can be manually deleted if needed, and can be executed multiple times to some extent)

When B. when js starts execution, it needs to load. js, module. exports tells Nodejs what to expose to the outside, such as. js exposes an object, including the name attribute and the doSomething method. Then the variable in B. js is actually the object.

After obtaining a. js, return to B. js. global. a_name declares a global variable, which is similar to window. a_name = a. name in the front end.

After the final process is completed, c. js executes the output value.

5. asynchronous underlying principle

NodeJS is easy to give people the illusion of use, that is, writing for a long time may not know how the underlying Asynchronization is implemented. (The following is mainly based on the understanding of asyncio in python3.4. If you have any mistakes, please note ).

The underlying libev of NodeJS uses IOCP in the Window and the ibeio Based on AIO in * nix to implement Asynchronization. At the system level, an application initiates an asynchronous request. After the system completes execution, the system notifies the application to complete processing. In this process, the application can suspend/push the previous processing into the thread pool for execution, while the application can execute other tasks during this period.

The entire operation is carried out through the system-level event loop. For example, Python provides methods like run_until and run_forever to ensure that the program will not end running before asynchronous execution. Imagine the entire asynchronous process as a working workshop. The machines in the workshop are responsible for viewing and stamping the packages. The workers get a package and then attach the corresponding labels to it, after the workshop is processed, the workers are handed back to the workers. The workers perform the next step based on the labels attached to the package and the labels attached to the workshop. The worker does not need to wait until the package inspection is completed before proceeding to the next step. He only needs to take simple processing and then put it into the workshop for inspection. Then, wait for the workshop to return a package to him, and then proceed to the next step.

At present, I only introduced some language-level knowledge, but there are still some distance from developing a complete web, which will be further introduced later. Including Redis, Nginx, and test driver.

The above is all the content of this article. I hope you will like it.

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.