node. JS Basic Knowledge Chowder
This period of time to do the project is mainly about the server function point, so, gradually began to learn node. JS Write server, overall down, think node is better than PHP, write service pre-processor faster, more efficient processing. Note: node is not dedicated to the server, in fact, node appears, JS from the Web front-end of the special language, into a common language. Node has a variety of basic modules: such as fs,path,buffer,http,net modules, in addition, node also has a wide range of three-party modules, such as writing server people commonly used express,co,koa,seqlize such as the famous framework, that is, three-party module. So what exactly is node. JS's module mechanism? What problems should we pay attention to on the module mechanism?
1. Some questions about the module mechanism of Nodejs
- What is the node. js module?
Node. JS's module mechanism complies with COMMONJS specifications, and the concept of COMMONJS definition modules is as follows:
- A separate file is a module. Each module is a separate scope, which means that variables defined in a file (also including functions and classes) are private and invisible to other files.
- The external interface of each file is the Module.exports object. All the properties and methods of this object can be imported by other files. We can define variables, functions, classes, and Module.exports by outputting this module.
- The module can be loaded multiple times, but only once at the first load, and then the result is cached and then loaded, and the cached result is read directly. To make the module run again, you must clear the cache.
- Require load the same module multiple times, the modules loaded are the same?
Here's a piece of code, and we'll look at the code as an example:
Module1 module:
var num=1;module.exports.num=num;` a 文件: `var module1=require("./module1"); var module2=require("./module1"); module1.num=2; console.log(module2.num);
What is the result of running the code above? A lot of people should answer 2, and the answer is 2, but what if the following scenario is true?
' Module1 module:
var num=1;module.exports.num=num
A file:
`var module1=require("./module1");module1.num=2;`
B File:
var module2=require("./module1");console.log(module2.num)
Now, run a file first (note that when a file is finished running, node does not end), and then run the B file, what is num? A lot of people here will say, apparently 1. This is a kind of inertia thinking, in fact the answer is 2, why? Because modules are loaded in the same file or in different files, if they are loaded, their caches are preserved, that is, they are only loaded once. So, after the a file is run, the NUM value of the Module1 module is modified to 2, and when the B file is run, the Module1 module is loaded, so the NUM value is displayed as 2 in the B file.
- Are the variables and functions in the module static?
Yes. Because the COMMONJS specification, the module is loaded once, each time the module is loaded is the same instance, and the static variable or function is the same. Therefore, for node, the variables and functions between the modules are static.
Compare the required mechanism of node with the import mechanism of Java?
For node, the ingest module uses the Require command, and Java is the import command. The basic function of node's require command is to read in and execute a JavaScript file and then return the module's exports object. The import of Java is to introduce a class file and then access the method or variable in the file through the class file name.
As you can see, node's require and Java import have similar design ideas:
- Both are scoped by file (module)
- Both have access control: Java has priavte,public access symbols, and node has exports whether the output determines the variables in the file.
The difference between the two is:
- The introduction of the 1.node require command is a module object, and the Java Import command introduces a class.
- After the 2.node required command introduces a module object, we can directly access some of the properties, functions in the module object, but Java may need to instantiate an object through a class and then access some properties of the object, of course, A static variable on a class in Java that can be accessed without instantiation.
2. Some questions about the function of JS
function is one of the most important things in JS, in the Java language, the function is just a function of the traditional sense, execute a function, access the object's code area, then assign the space of the object to the parameter, then execute the function and then return the value. However, for JS, functions are not just functions, functions can also be used as variables, parameters, return values, functions and even JS as a basic type, right! The function in JS is an object type, also means that the function in the JS in the existence of an object. In fact, the function as a basic type, it also shows the flexibility of the function. Well, we need to analyze how the JS function is implemented.
JS has two common methods of defining functions:
function A(){}` `var a=function(params){}
How does the above method be implemented in memory? In fact, it is very simple, look at the following memory allocation diagram will understand:
In fact, in the above method, either the first method or the second method, in the JS interpreter, will do this:
var x=newObject x.constructor=A; ` `A.prototype=x
The x here is the object on the right. As you can see, the function of JS is essentially pointing to a heap of space (since there is already a prototype: A.PROTOTYPE=OBEJCT). This also gives a good explanation of why functions can be used as parameters and return values, because a function name, as a parameter, represents a block of address values on a heap of space. The above two methods, the difference is the first method, Name=a, and the second method of name=undefined.
So, it is now possible to explicitly write a node or JS program when the idea: when I define a function, then, then, in the heap space to define an object, and then use the function name to represent the object's ground value, when called, that is, access to the object, then, then allocate the stack space, execute the code snippet , and then execute the function.
3.js type, parameter, scope, closure
- JS is a language that does not do type checking, then what are the types of JS? The basic types of JavaScript advanced programming are divided into basic types and object types, and the underlying types are: Boolean type, Shaping, string,undefined, and null. The object type includes Object,funtion,array,date. (Again, it can be seen that funtion is the object type)
- JS in the definition of function parameters, not write type declaration (which is also a disadvantage of JS), so when invoking the JS function, the programmer must pay attention to the type. The problem with parameters is that it is common in the project to confuse the string type of JSON with the type of object, the use of function type errors, and so on.
-
Scope: The question about the scope of JS, learn more about this blog: JS scope, about the scope of the JS traditional problem, here simple:
- 1.JavaScript is a scope chain exists. The
- 2.JavaScript does not have a block-level scope. The
- 3.JavaScript has the feature of variable elevation.
- 4. Inside the function body, the local variable takes precedence over the global variable with the same name (local variables obscure the scope of the global variable)
We can see that due to the scope of JS, we may have some problems, such as the following function:
var1; function bar() { if (!foo) { var10; } console.log(foo); }bar();
What is the result of the execution? A lot of people will say is 1, but, because JS function internally defined variable priority is higher than the external, coupled with the reason for JS variable promotion, therefore, the execution of the above implementation of the result is 10;
Look at this function again:
function test () { console.log(value); ‘something‘; console.log(value);}
Such writing in other block-level scope is obviously not compiled through, but in JS can, but also because of the JS variable promotion, can be compiled through, the output is undefined and something.
The above problem is that JS's scope design problem brings bad results, such as no block-level scope and variable promotion problems, will bring some undesirable results in programming. These problems, in the ES6 specification, with let instead of Var, are resolved. For example, the first of the above questions, you can use let instead of Var: for example, this solves:
var1;function bar() { if (!foo) { let10; } console.log(foo);}bar();
4.js There are several ways to instantiate an object?
In the case of JS, there are several ways to instantiate an object:
1. Written statement:
var person = { "lbq", 22, function () { returnthis.name; }}console.log(person.getName());
As you can see, creating an object like this is really simple, as long as a Huanguo is available, which is the most convenient point for JS to create objects.
2. Use the function to create:
function person (name,age) { this . Name=name; this . Age=age; this . Getname=function () { return this . Name; }}var person1=new person ( "LBQ" , 23 ); var person2=new person ( "LZW" , 22 ); Console.log (Person1.getname ()); Console.log (Person2.getname ());
As you can see, the second method is to construct the generated object through function, here we can see that JS before ES6, there is no concept of class, we want to construct objects, only through function to generate.
- Prototype-generated objects:
function Person2(name, age) { This. name = name; This. Age = Age;} Person2.prototype.getName = function () { return This. Name; Person2.prototype.getAge = function () { return This. Age;varperson3=NewPerson2 ("LBQ", at);varperson4=NewPerson2 ("LZW", A); Console.log (Person3.getage ()); Console.log (Person4.getage ());
In JS, each function has a prototype attribute, which is a pointer to an object, which is the prototype object. We can make a variable definition and a method definition for the prototype object, and then instantiate an object with new, and the instantiated object will have a--proto-, pointing to the prototype object. A detailed description of the prototype object can be found in the sixth chapter of the book, "JavaScript Advanced Programming".
- ES6 the new syntax, instantiate an object with the Class keyword:
class person3 { Constructor (name,age) {this . Name=name; this . Age=age; } getName () {return this . Name; } getage () {return this . Age; }}var person5=new Person3 ( "LBQ" , 23 ); var person6=new Person3 ( "LZW" , 22 ); console . Log (Person5.getname ()); console . Log (Person6.getname ());
The good news is that in ES6, after adding the class keyword, we can define the class in JS, like Java, and then instantiate an object through the class.
Understanding of the This keyword for 5.js
This key is probably well understood in Java, because JS is an object-oriented language, so this in Java is a pointer to the current object, we can access the current object's member variables or methods (whether public or private), but JS is a functional programming language, JS in this How to understand it?
About JS This understanding, may be said to be more complex, here I give my own understanding: the function that appears with the This keyword, which object is defined in the function, then the object is thi point to the object:
Let's look at the demonstration:
var obj={};
obj.x=100;
obj.y=function (){console.log(this.y)};
obj.y();
Here is a good understanding: Obviously the print is 100, because the function y is called in the obj variable, so thi points to the Obj object, this.x is 100.
Now let's look at a difficult demonstration:
var showthis=function () {
Console.log (this.x);
}
var x= "This is a variable of window";
var obj={};
obj.x=100;
Obj.y=function () {Console.log (this.x)};
var y2=obj.y;
Obj.y ();
Showthis ():
Y2 ():
In the above code, altogether to print three console, according to analysis, one certainly or 100, the second one? There is a rule in the scope of JavaScript variables that "Global variables are properties of Window objects." Therefore, the Showthis function variable is defined in the Window object, so showthis prints the This is a variable of window. So, what about the Y2 object? The Y2 object is also defined in the Window object, so the result of the third console must also be this is a variable of window.
In the above two cases, we can see that this is a pointer to the object where the function is located, if the function is global, then this is pointing to the Window object.
Thinking about this point, I was building a Web project from node to understand, because in KOA, often using this.request or this.body to refer to the message request and response to HTTP, so, sometimes it is important to pay attention to the program in the this point. If you want to change the context of this, you can use call or apply.
These are some of my key questions in the Beginner node. js, such as how JS functions as a first-class citizen, memory allocation long what kind of, there is a beginner language should master the basis: variable type, scope, often err on the key word, the establishment of dependency system, not to learn node should pay attention to, but learn any language Should be noticed and mastered.
node. JS Basic Knowledge Chowder