Nodejs Learning Notes in the introductory chapter _node.js

Source: Internet
Author: User
Tags closure

Share the first article about Nodejs--javascript's common knowledge and how to transition from Javascript developers to Nodejs developers (no specific framework is introduced). Before reading this article, I hope you have some preliminary knowledge of JavaScript.

Javascript is an interpretive language of a prototype model. The explanatory type will be discussed in later Nodejs, the prototype chain is one of the object-oriented implementations of Javascript before ES6, and the class supported in ES6 adds a new way of implementation. Everything in Javascript is an object, including "class." It is very familiar to the metaprogramming of Ruby/python, and Javascript is also very easy to implement the dynamic generation of class methods.

1. Simple "class" based on prototype chain implementations

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 specifications, such as all the methods in Javascript are named Hump, priority to use single quotes, two spaces, and so on, more specifications can refer to Https://github.com/airbnb/javascript.

The Staticsay in the code is a static method, that is, it can only be invoked through Person.staticsay. When the person above generates an instance, such as var Vincent = new Person (' Vincent '), Vincent automatically inherits all methods of Person.prototype (this in code refers to the current context, that is, the The Vincent in the article).

You can also dynamically add methods to 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 the prototype. For example, the following is implemented with worker.prototype = new Person (), all the methods and attributes of the instance object returned by the new person () are assigned to the prototype, which simulates the inheritance in disguise. In this way, the final layer of the prototype is found inside the content (because each instance has a method inside the prototype, up to Object). Of course, you can also use traversal to simulate inheritance by assigning values to prototype.

2. Context switching

The most intuitive manifestation of the context is this in the code block, which is typically used in object-oriented programming to refer to the corresponding instance generated by the current class, consistent with the self of the other language.

To continue with the example above, a Person.prototype.sayHi method has already been implemented, and now I have a new object with the following code:

var Cat = function (name) {
 this.name = name;
}

var c = new Cat (' Tomcat ');

If one day suddenly the whimsical hope that this cat as a person to introduce himself to do, he did not sayhi this method. But can pass Console.log (Person.prototype.sayHi) can get human sayhi method, how to let the cat also can use?

Javascript has two methods, call and apply, and their difference is that the parameter is different (Google itself), the role is to switch context. To put it simply, you can change this to another object in the Person.prototype.sayHi function. Use mode: Person.prototype.sayHi.call (c).

Is this practical? For example, the following scenario:

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

In the above function, all parameters are obtained by keyword arguments to support an indefinite number of arguments. Now we want to use some of the Array-type methods for persons, how do we implement them? This can be achieved by context switching:

var dosomething = function () {
 var persons = arguments;
 Using the slice method of array, convert the arguments object to the array instance
 var Persons_arr = Array.prototype.slice.call (arguments);

3. Closure of the package

First comes the common code

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

What will this output be? Output 0 1 2 in turn? The reality is that when settimeout the first time the callback is executed, the for loop is over, meaning I is already 3 at this point, resulting in the final output of 3 3 3.

When you need to protect a variable so that he is not affected by the perimeter code, you might want to consider the closure-a block of code that encloses the scope.

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

Yi, + is why, there is no other way to achieve, please Google yourself. The scope of I in the closure is a closed scope, so the final closure of I has not been changed by the outside execution, so it can successfully output 0 1 2.

With a simple introduction to JavaScript features, keyword prototype chains, call and apply, arguments keywords, more suggestions can be made on books such as the authoritative guide, or a quick understanding of the basic types and the methods of each type. Some of the more magical code, such as getting the string of the current code, and then processing it to get what you want, using getter and setter to do some special action when the user Gets or assigns the object's properties, and so on.

4. The development difference between Nodejs and Javascript

This piece mainly introduces the basics of require loading, first introduce some code:

A.js
module.exports = {
 name: "A",
 dosomething:function () {return
  "something";
 }
}

//B.js
var a = require ('. a ')
global.a_name = a.name;

C.js
require ('./b ');
Console.log (A_name)//post-execution print a 

What happens when we execute node c.js?

Require is the Nodes keyword, although nodejs is known for its asynchrony, but his require are blocked. Otherwise, there will be instances in which the following code has already been executed without loading other modules.

The Require.resolve () method is used to find out the actual path of the file you are referencing, find out if there is a cache in Require.cache, and then read the file and then parse it, so normally, a JS The code that executes in the file is executed only the first time it is require. (Tip. Require.cache can delete something manually if necessary, and can be executed several times in some way.

When B.js begins to execute, he needs to load a.js,module.exports to tell Nodejs what the file is exposed to, such as a.js exposing an object, including the Name property and the DoSomething method. Then the a variable in b.js is actually the object.

After you finish getting a.js, continue back to B.js, global.a_name equivalent to declaring a global variable, which is similar to the Window.a_name = A.name effect in the front end.

The final process completes and the c.js executes the output value.

5. The underlying principle of asynchrony

Nodejs is very easy to give people an illusion of use, is written for a long time may not know how the underlying asynchronous is how to achieve. (The following understanding is mainly from the understanding of the Asyncio in the python3.4, if there are errors welcome to point out).

The Nodejs bottom Libev are implemented asynchronously under Windows using IOCP and *nix under the AIO Libeio. Through system-level technology, the end result is that the application initiates an asynchronous request, and eventually the system notifies the application that the process is complete after the system has finished executing. In this process, the application can suspend/push the previous processing to wait for execution in the thread pool, and the application can perform other tasks during this period.

The entire operation operates through a system-level event loop. Python, for example, provides a method similar to Run_until and run_forever to ensure that the program does not end running until it is executed asynchronously. Think of the whole asynchronous as a working workshop, the machine in the workshop is responsible for viewing the parcel and stamping the operation, the worker got a parcel, then put on the corresponding label, and then back to the workers after the workshop, workers according to the package on the label before him and by the shop affixed to the label, Proceed with the next step. The worker does not have to wait for the parcel to be checked for the next one, he only needs to accept the simple process and then put it into the workshop for inspection. Then wait for a certain time the workshop returned to him a package, he went to the next step.

At present, only a few language level knowledge, but only these distance to develop a complete web and some distance, will continue to introduce later. Including Redis,nginx, test drivers, and so on.

The above mentioned is the entire content of this article, I hope you can enjoy.

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.