An introduction to learning notes

  • 2020-05-30 19:26:05
  • OfStack

Share article 1, common knowledge about NodeJS -- Javascript and how to transition from Javascript developer to NodeJS developer (no specific framework). Before reading this article, I hope you have some idea of javascript.

Javascript is an interpreted language for prototype models. The interpretive type will be discussed later in NodeJS. The prototype chain is one of the object-oriented implementations of Javascript before ES6, and a new implementation of class is supported in ES6. Everything in Javascript is an object, including "classes." This may sound familiar to anyone who has worked with the metaprogramming of ruby/python, and Javascript is easily a way to implement dynamically generated classes.

1. Simple "class" based on prototype chain implementation


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

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

Person.prototype.sayHi = function(){
 Person.staticSay(this.name);
}

1 some common specifications, such as naming Javascript all methods is the hump, give priority to use single quotes, two Spaces, etc., more specification can reference https: / / github com/airbnb/javascript.

staticSay in the code is a static method that can only be called through Person.staticSay. When Person above generates an instance, for example var vincent = new Person('vincent'); , vincent automatically inherits all methods of Person.prototype (this in the code refers to the current context, vincent above).

At the same time, you can dynamically add methods to 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, Worker.prototype = new Person() is used for the following implementation. All the methods and properties of the instance object returned by new Person() are assigned to prototype, which is a disguised simulation of inheritance. This way you end up one layer at a time looking up the contents of prototype (because every instance has a method in prototype, up to Object). Inheritance can also be simulated by assigning prototype through a traversal.

2. Context switching

The most intuitive representation of the context is this in the code block, which is usually used in object-oriented programming to refer to the corresponding instance of the current "class" generated, as opposed to self1 in other languages.

Continuing with the example above, I have implemented 1 Person.prototype.sayHi method, and now I have a new object. The code is as follows:


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

var c = new Cat('tomcat');

If one day suddenly fantastical hope that the cat like human 1 to introduce himself how to do, he does not have sayHi this method. But you can get the human sayHi method by console.log (Person.prototype.sayHi), so how can you get a cat to use it?

Javascript has two methods, call and apply. The difference between them is that they have different parameters (Google) and are used to switch context. Simply put, you can turn this in the function Person.prototype.sayHi into other objects. Method of use: Person. prototype. sayHi. call (c).

Is this practical? For example, in the following scenario:


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

In the above function, an indefinite number of parameters are supported by fetching all the parameters via the keyword arguments. Now we want to use 1 of the original Array types for persons. How do we do that? This can be done with a context switch:


var doSomething = function(){
 var persons = arguments;
 //  use  Array  the  slice  Methods,  arguments  Object to  Array  The instance 
 var persons_arr = Array.prototype.slice.call(arguments);
};

3. The closure

Let's start with some common code


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

What is this going to output? I'm going to output 0, 1, 2, right? The reality is that by the time setTimeout executes the first callback, the for loop has ended, which means that i is already 3, resulting in a final output of 3, 3, 3.

When you need to protect a variable from peripheral code, you might want to consider a closure -- a closed scoped block of code.


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

Hey, what is +? Is there any other way to achieve it? Please Google by yourself. The scope of i inside the closure is a closed scope, so eventually the i 1 inside the closure is not changed by the outside execution, so it can successfully output 0, 1, and 2.

A brief introduction to some of the features of javascript, the keyword prototype chain, call and apply, arguments keywords, and more Suggestions can be found in books such as the authoritative guide, or a quick look at the basic types and the methods available for each type. There is some magic code, such as get the string of the current code, then process it to get what you want, use getter and setter to do some special operations when the user gets or assigns the properties of the object, and so on.

4. Development differences between NodeJS and Javascript

This section mainly introduces the basic knowledge of require loading. First, it introduces 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) //  Print after execution  a 

What happens when we execute node c.js?

require is the nodes keyword, and while NodeJS is known for its asynchrony, its require is blocked. Otherwise, the following code will be executed before the other modules have been loaded.

The require.resolve () method is used to find out the actual path of the file you are referencing. After finding out, Nodejs will look in require.cache to see if there is a cache. (tip.require.cache you can manually delete something if you need to, and then you can sort of do it multiple times.)

When b.js starts to execute, it needs to load a.js, module.exports to tell Nodejs what the file is exposed to. For example, a.js exposes an object containing name properties and doSomething methods. And then the a variable in b.js is actually this object.

After getting a.js, go back to b.js, global.a_name and declare a global variable, which is similar to window.a_name = a.name in the front.

When the final process is complete, c.js executes the output value.

5. The underlying principle of asynchrony

It's easy to get the illusion of using NodeJS without knowing how the underlying asynchrony is implemented. (the following understanding mainly comes from the understanding of asyncio in python 3.4, if there are any mistakes, please point out).

The underlying NodeJS USES IOCP under Window and libeio under *nix under AIO to achieve asynchrony, respectively. Through the technology of system level, one purpose is finally achieved, that is, the application program initiates an asynchronous request, and finally, after the execution of the system, the system notifies the application program to complete the processing. During this process, the application can suspend/push the previous processing into the thread pool to wait for execution, while the application can perform other tasks.

The entire operation operates through a system-level event loop. For example, Python provides methods like run_until and run_forever to ensure that the program does not end before asynchronous execution. Will think the asynchronous as 1 1 straight in the operation of the workshop, workshop inside the machine is responsible for check the package and seal of this operation, the workers received a parcel, and then after the corresponding label, such as workshop after the treatment given back to the workers, the workers according to the package and the label before he was labeled the workshop, the next step 1. The worker does not have to wait for the package to be checked before moving on to the next one. Instead, he simply accepts the package and puts it into the workshop for inspection. Then wait for a certain time the workshop return to him a certain package, he went to the next step of the operation.

At present, we have only introduced some language knowledge, but only these are still some distance from developing a complete web, which will be introduced later. This includes Redis, Nginx, test drivers, and so on.

That's all for this article, I hope you enjoy it.


Related articles: