Home  >  Article  >  Web Front-end  >  NodeJs basic syntax and types_node.js

NodeJs basic syntax and types_node.js

WBOY
WBOYOriginal
2016-05-16 16:14:181494browse

is written in front

Today I want to check the knowledge about the type of Node. I want to summarize it. I saw an article on Googol, but the original link is no longer there. Pull this article out in the snapshot. If the original author has any questions , please contact me!

This article is all about the basics of JS, experts will automatically skip it! I haven't written much about js before, and I'm relatively weak in this area, so I also encountered trouble when writing node. I'll add some knowledge to myself here!

Text

Node.js is based on the JavaScript scripting language. A common feature of most scripting languages ​​is "weak typing".

Different from PHP, PHP does not need to declare a new variable even if it has a new variable, while JavaScript still needs var to declare it. And this var covers the meaning of all types such as int, string, char, etc. in C, even functions.

All the contents of this and the following articles are edited using vim under Linux or Cygwin (if not, please convert it to your own method), and then view the results on the command line.

Basic Grammar

Variable declaration

In C/C, we declare variables like this:

```C

Copy code The code is as follows:

void foo() {}
int a = 0;
char b = 'a';
float c = 1.0f;
void (*d)() = foo; ///< I forgot whether it was written like this, but it is a function pointer

And in Node.js it looks like this:
```javascript

Copy code The code is as follows:

function foo() {}
var a = 0;
var b = 'a';
var c = 1.0;
var d = foo;

So, no matter what type of variable it is, it is solved with a var in Node.js.

Loop statement

for…i

This loop statement is basically the same as C/C, both are

```C

Copy code The code is as follows:

for(int i = 0; i < foo; i )
{
//...
}

Since Node.js is weakly typed, you only need:
```javascript

Copy code The code is as follows:

for(var i = 0; i < foo; i ) {
//...
}
for…in

This is a post-typed loop statement, similar to PHP’s foreach.

For example, we have a JSON object as follows:

javascript

Copy code The code is as follows:

var foo = {
"hello" : "world",
"node" : "js",
"blahblah" : "bar"
};

At this time we can use for...in to loop through:

javascript

Copy code The code is as follows:

for(var key in foo) {
console.log(key ": " foo[key]);
}

If we enter the following command on the command line:

Copy code The code is as follows:

$ node foo.js

The following content will be displayed on the screen:

Copy code The code is as follows:

hello
: world
node: js
blahblah: bar

Tips: As you can see from the above, the for...in statement is used to traverse the key names of JSON objects, arrays, and objects, but does not provide key value traversal. If you want to get the key value, you can only get it in the form of foo[]. This is somewhat different from PHP's foreach.

while…do, do…whill

I won’t explain this much. It’s not much different from other languages. It’s just that if there is a variable declaration, you need to use var.

Operator

, -, *, /

That’s it for these operators. What you need to pay attention to is . It can operate on both strings and numeric operations. Although weakly typed languages ​​say that the type is weak, numbers can sometimes appear in the form of strings, and strings can sometimes appear in the form of numeric values. However, when necessary, we still have to say what type it is. We can Use the following code to see the result:

Copy code The code is as follows:

var a = "1";
var b = 2;
console.log(a b);
console.log(parseInt(a) b);

The parseInt here is a built-in function of Node.js, which is used to parse a string into a variable of type int.

The execution result of the above code is:

Copy code The code is as follows:

12
3

Note: The first console.log result is 12. Since a is a string, b is also added by the system as a string. The result is that the two strings are glued together and become 12. The second console.log result is 3 because we converted the first a to int type. The addition of two int type variables is the sum of values. The result is of course 3.

==, ===, !=, !==

One thing to explain here is that when the length of this logical operator is 2 (==, !=), it only determines whether the external values ​​are the same, but does not determine the type. Such as

Copy code The code is as follows:

var a = 1, b = "1";
console.log(a == b);

The result it outputs is true . But if we add an equal sign in the middle of the judgment, then it will be a strict judgment. Only when the type and value are the same will it be true, otherwise it will be false. That is to say

Copy code The code is as follows:

var a = 1, b = "1";
console.log(a === b);

, the returned result is false, because a is of int type and b is a string.

Let’s talk about conditional statements by the way. In fact, if here is no different from other languages. It is just a matter of several logical operators, two equal signs and three equal signs. So I won’t go into too much detail.

typeof

Here I will treat it as an operator rather than a function.

The function of this operator is to determine the type of a variable. It will return a string, that is, the type name. You can know it by executing the following code:

Copy code The code is as follows:

function foo() {}
var a = 0;
var b = 'Shh~ Egg Drop Soup is sleeping. ';
var c = 1.0;
var d = foo;
var e = { "a" : a };
var f = [ 1, 2, 3 ];
var g = null;
var h = undefined;
console.log(typeof a);
console.log(typeof b);
console.log(typeof c);
console.log(typeof d);
console.log(typeof e);
console.log(typeof f);
console.log(typeof g);
console.log(typeof h);

The execution result here will be:

Copy code The code is as follows:

number
string
number
function
object
object
object
undefined

null, undefined, NaN

In JavaScript, there are three special values, as shown in the title. The first one may be familiar to everyone. It is also found in C/C, but it is capitalized. Its essence is a

```C

define NULL 0

In JavaScript, these three values ​​have different meanings.

### null ###

null is a special kind of object, which roughly means empty. For example:

var a = null;
Everyone can understand it, so I won’t explain it too much. But unlike C/C, this null is not equal to 0.

### undefined ###

This thing means that this variable is not declared. In order to better distinguish null, our sample code is as follows:

```javascript

Copy code The code is as follows:

var a = {
"foo" : null
};
console.log(a["foo"]);
console.log(a["bar"]);

In the above code, we make the value of a["foo"] empty, that is, null. And there is no declaration of a["bar"] at all, it is not even empty. Everyone should have guessed the output result:

Copy code The code is as follows:

null
undefined

NaN

This is an empty value, a special number. Its full name is Not a Number. It's a bit strange. You can understand it as a number type variable that is not in digital form or has an incorrect value.

Mostly occurs when floating-point numerical operation errors (such as division by 0) occur. It can even be the user himself making a variable equal to NaN in order to return an error value to let everyone know that this function operation has gone wrong.

Little offal

The other remaining statements are similar to other existing languages, such as break, switch, continue, etc.

Variable type

This section mainly talks about JavaScript objects, and other types will be almost passed over.

Basic Type

Node.js contains almost the following basic types:

number
string
boolean
array
Among them, the first three types can be directly assigned, and the assignment of array is just a reference assignment. If a value is changed in the new variable, the value of the old variable will also change. You can directly try the following code:

javascript
var foo = [ 1, 2, 3 ];
var bar = foo;
bar[0] = 3;
console.log(foo);
The result it gets is:

javascript
[ 3, 2, 3 ]
In other words, if array copies a new array, it cannot use direct assignment, but must "deep copy".

It is necessary to talk about the three creation methods of array.

First type:

javascript

Copy code The code is as follows:

var dog = new Array();
dog[0] = "Shh~";
dog[1] = "Egg Drop Soup";
dog[2] = "Sleeping";

Second type:

javascript

Copy code The code is as follows:

var dog = new Array( "Shh~", "Egg Drop Soup", "Sleeping" );

The fourth type:

javascript

Copy code The code is as follows:

var dog = [
"Shh~",
"Egg drop soup",
"Sleeping"
];

I personally prefer the third way of writing, which is more concise.

JSON object

Here I separate the JSON object instead of classifying it as a JavaScript object. If you feel that I am a bit misleading, you can skip this section directly.

My distinction between JSON objects and JavaScript objects lies in whether they are only used to store data, rather than instantiating a class. In fact, the essence of JSON is JavaScript Object Notation.

For more information about JSON, please encyclopedia yourself.

Declaring a JSON object in Node.js is very simple:

javascript

Copy code The code is as follows:

var dog = {
"pre" : "Shh~",
"sub" : {
"name" : "Egg Drop Soup",
"act" : "sleeping",
"time" : 12
},
"suf" : [ "I said", "It's sleeping", "It's just sleeping" ]
};

There are two ways to get the key value of a certain key name in the JSON object. The first is to use dot connection, and the second is to use square brackets:

javascript

Copy code The code is as follows:

dog
.pre;
dog["pre"];

Note: When using dot above, it is directly followed by the key in JSON. If you treat the key as a variable, you can only try it with dog[key]: Now you can try it yourself, use The for...in form traverses the above JSON object. Don’t forget to use typeof meow~

Basics of classes (objects)

Strictly speaking, a Node.js class cannot be regarded as a class. In fact, it is just a collection of functions with some member variables. Its essence is actually a function.

But for the sake of simplicity, we will refer to it as "class" and the instantiation as "object" in the following and future.

Because a class has many function characteristics, or its essence is a function, we may accidentally explain the basics of functions here.

Declaration and instantiation of classes

Declaring a class is very simple, don’t laugh:

javascript
function foo() {
//...
}
Okay, we've written a foo class.

Real or fake? ! real.

Don’t believe it? If you don’t believe it, you can type a piece of code and take a look:

javascript
var bar = new foo();
Regardless of whether it is a function, if it is written in this form (new), it is an instantiation of this class.

And this so-called foo() is actually the constructor of the foo() class.

Member variables

There are two ways to use member variables.

The first is to use this. in the constructor of the class or any constructor. You can declare a member variable at any time, and it does not affect its use externally. Anyway, even if you use it before it is declared, there will be an undefined to support it. So this is the first method:

Copy code The code is as follows:

javascript
function foo() {
This.hello = "world";
}

Note: Only when this is added, it is a member variable of the calling class, otherwise it is just a local variable within the function. It is necessary to distinguish the scope of the variable when there is no this.

The second method is to declare it outside the constructor or any member function. The format is .prototype.:

javascript

Copy code The code is as follows:

function foo() {
//...
}
foo.prototype.hello = "world";

No matter which method above is a declaration of member variables, we can see the effect:

javascript

Copy code The code is as follows:

var bar = new foo();
console.log(bar.hello);

You can even modify this class like this:

javascript

Copy code The code is as follows:

function foo() {
This.hello = "world";
}
foo.prototype.hello = "Egg Drop Soup";

Then use the above code to output.

Think about why the output is still world instead of egg drop soup.

Constructor

We said before that foo() is actually a constructor. So obviously we can pass parameters to the constructor, so we have the following code:

javascript

Copy code The code is as follows:

// Code 2.1
function foo(hello) {
If(hello === undefined) {
This.hello = "world";
} else {
This.hello = hello;
}
}

We see a strange judgment above if(hello === undefined). What is the use of this judgment? The first possibility is that the developer went out of his way to pass undefined in. At this time, it is understandable that it is undefined.

There is another situation. We said at the beginning that JavaScript is a weakly typed language. In fact, it is not only weakly typed, but its parameter passing is also very loose. You can pass more or less (as long as you can ensure that the program does not make errors or the logic does not make errors when you pass more or less), in principle it is okay. Parameters passed in more will be automatically ignored, while parameters passed in less will be complemented with undefined.

Look at the following code to understand:

javascript

Copy code The code is as follows:

// Continued from code 2.1
var bar1 = new foo();
var bar2 = new foo("Egg Drop Soup");

Please output the hello variables of the two bars by yourself, and you will find that one is world and the other is egg drop soup. Obviously, when our first bar1 is declared, Node.js automatically sees it as:

javascript

Copy code The code is as follows:

var bar1 = new foo(undefined);

So there is a saying that it is world.

Also, in this constructor, we see that the parameter passed in is hello, and there is a member variable in this class called this.hello. However, we have said before that the scope is different when there is this and without this. The parameter only acts in the constructor, and the one with this is a member variable. Using this immediately distinguishes them, so it doesn't matter even if they have the same name.

Member functions

Member function declaration

The declaration of member functions is similar to the second declaration method of member variables, that is, .prototype. = ;

javascript

Copy code The code is as follows:

// Continued from code 2.1
function setHello(hello) {
this.hello = hello;
}
foo.prototype.setHello = setHello;
bar1.setHello("Egg Pancake");

The above code is obvious. We have implemented the setHello function of the foo class, which can modify the value of foo.hello.

But isn’t it a bit troublesome to write like this? Next I am going to talk about an important feature of JavaScript functions.

★ Anonymous function ★

Many times some of our functions are only referenced or called in one place, so it is not worthwhile and unnecessary for us to give this function a name, so we can temporarily write this function and directly let the person who refers to it People quote it, people who call it call it. Therefore, the function name can be omitted, such as:

javascript

Copy code The code is as follows:

function(hello) {
This.hello = hello;
}

As for how to quote or call? If the above class needs to be referenced, it would be written like this:

javascript

Copy code The code is as follows:

foo.prototype.setHello = function(hello) {
This.hello = hello;
}

This way of writing has the same effect as member function declaration, and saves a lot of code. And in fact, basically the declaration of class member functions is declared in this anonymous function way.

As for how to make the anonymous function be called? This is usually used when passing in a function that is only called by a certain function.

For example, we have a function whose prototype is:

javascript

Copy code The code is as follows:

/**
* We will pass in two variables a and b,
* After calculating the value of a b, hand it over to func(num)
* Go to output
​*/
function sumab(a, b, func) {
var c = a b;
func(a, b, c);
}

For example, we have two versions of the output function, one is Chinese output and the other is English output, then if the anonymous function is not used, it is written like this:

javascript

Copy code The code is as follows:

function zh(a, b, sum) {
console.log(the value of a " " b " is: " sum);
}
function en(a, b, sum) {
console.log(a " plus " b " is " sum);
}
sumab(1, 2, zh);
sumab(3, 4, en);

Execute this code once, the output result will be:

The value of 1 2 is: 3
3 plus 4 is 7
If such code is in the form of an anonymous function, it will be:

javascript

Copy code The code is as follows:

sumab(1, 2, function(a, b, sum) {
​ console.log(the value of a " " b " is: " sum);
});
sumab(3, 4, function(a, b, sum) {
console.log(a " plus " b " is " sum);
});

This form is usually used for callback functions. The callback mechanism is the essence of Node.js or JavaScript. It will be introduced in future chapters.

Anonymous function declaration method of member function declaration

Although I mentioned it in the previous section, let’s talk about it again.

Usually when we declare member functions of a class, we use anonymous functions to declare them, because that function is just a member function of this class anyway and will not be referenced or called separately from other places, so there is the following Code:

javascript

Copy code The code is as follows:

// Continued from code 2.1
foo.prototype.setHello = function(hello) {
This.hello = hello;
}

In this way, we make the foo class have the setHello function.

2.3.4. Arbitrariness of classes

This is nonsense from me again. The so-called arbitrariness of classes means that you can modify your class anywhere in JavaScript, which has certain similarities with Ruby.

For example, string is actually a class, with member variables such as length, and member functions such as indexOf and substr. But in case we feel that this string is imperfect in some places and want to add our own method, then we can add a function to it where you want, such as:

javascript

Copy code The code is as follows:

String.prototype.sb = function() {
var newstr = "";
for(var i = 0; i < this.length; i ) {
If(i % 2 === 0) newstr = "s";
else newstr = "b";
}
Return newstr;
};

The meaning of this function is to fill a string so that it becomes the incarnation of sb.

Let’s test it out:

Copy code The code is as follows:

var str = "Shh~ Egg Drop Soup is sleeping.";
console.log(str.sb());

You will get this result:

sbsbsbsbs
If you tell your computer "Shh~ Egg Drop Soup is sleeping.", your computer will call you an idiot four and a half times. (Smash it quickly)

3. Attached

3.1. Deep copy

The so-called deep copy means to create a new array or object by yourself, and manually copy the basic type variable values ​​​​in the source array or object one by one, instead of just taking the reference of the source array or object. So this involves a recursive call or something.

The following is a deep copy function I implemented. You can write your own and add it to your own Node.js knowledge base.

javascript

Copy code The code is as follows:

function cloneObject(src) {
  var dest = {};
  for(var key in src) {
    if(typeof src === "object") dest[key] = cloneObject(src[key]);
    else dest[key] = src[key];
  }
  return dest;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to implement tap event to prevent bubbling in zepto.js_javascript skillsNext article:How to implement tap event to prevent bubbling in zepto.js_javascript skills

Related articles

See more