Nodejs basic syntax and type _node.js

Source: Internet
Author: User
Tags anonymous constructor define null logical operators php foreach knowledge base

It's written in front.

Today want to check the type of node what kind of knowledge, want to summarize, see an article on the googol, but the original link is not, in the snapshot to pull out this article, if the original person has a problem, please contact me!

The article is some of the basis of JS, Master automatically skipped! I have not been how to write JS, this aspect is weak, so in the writing node when also encountered trouble, here to add their own knowledge!

Body

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

Unlike PHP, PHP has a new variable that doesn't need to be stated, and JavaScript needs to be declared by Var. This var covers all types of int, string, char, and so on in C + +, and even function.

All content in this and later sections is edited using Vim under Linux or Cygwin (if not, turn yourself into your own method) and then view the results at the command line.

Basic syntax

Variable declaration

In C + +, we declare variables in the following way:

"" C + +

Copy Code code as follows:

void foo () {}
int a = 0;
Char b = ' a ';
float C = 1.0f;
void (*d) = foo; < forgot it was written like this, anyway, it's a function pointer.

And in the Node.js, it's like this:
"JavaScript

Copy Code code as follows:

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

Therefore, no matter what type of variable, in the Node.js is a var to solve.

Loop statement

For...i

This loop statement is basically the same as C + +,

"" C + +

Copy Code code as follows:

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

And since Node.js is a weak type, you only need to:
"JavaScript

Copy Code code as follows:

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

This is a back-type loop statement, similar to the PHP foreach.

For example, we have a JSON object as follows:

Javascript

Copy Code code as follows:

var foo = {
"Hello": "World",
"Node": "JS",
"Blahblah": "Bar"
};

This time we can use for...in to iterate through:

Javascript

Copy Code code as follows:

for (var key in Foo) {
Console.log (key + ":" + Foo[key]);
}

If we enter the following command at the command line:

Copy Code code as follows:

$ node Foo.js

The following content is displayed on the screen:

Copy Code code as follows:

Hello
: World
Node:js
Blahblah:bar

Hint: The for...in statement is used to traverse the key names of JSON objects, arrays, and objects without providing a traversal of the key values. If you want to get the key value, you can only get it by foo[< the current key name. There is a certain difference between this and the PHP foreach.

While...do, Do...whill

This is not much to explain, and other languages no big difference, nothing but if there is a variable statement, need to use Var is enough.

Operator

+, -, *, /

This is also true of these operators, and it should be noted that +. It can be used either as a string or as a numeric operation. Weak type language Although the type is weak, the number can sometimes appear as a string, strings can sometimes appear in numerical form, but when necessary to say what it is the type, we can use the following code to see the results:

Copy Code code 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 to parse a string into a variable of type int.

The above code execution results are:

Copy Code code as follows:

12
3

Note: The first console.log result is 12, because a is a string, B is also added by the system as a string gesture, and the result is that two strings are glued together and become 12. and the second Console.log result is 3, because we convert the first a to the int type, and the two int variables are added to the value, and of course it's 3.

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

Here's one thing to explain, when this logical operator has a length of 2 (= =,!=), it just determines that the external value is not the same, but does not judge the type. Such as

Copy Code code as follows:

var a = 1, b = "1";
Console.log (A = = B);

The result of this output is true. But if we add an equal sign to the intermediate judgment, then it is strictly judged that the type and value are the same when it is true, or false. Other words

Copy Code code as follows:

var a = 1, b = "1";
Console.log (A = = = B);

, the return result is false, because a is an int and B is a string.

Let's take the conditional statement, in fact, if this is the same as other languages, is a few logical operators two equals three equals. So there's no more tiredness.

typeof

I think of it as an operator rather than a function.

The function of this operator is to determine the type of a variable, return a string, that is, the type name, the specific execution of the following code will know:

Copy Code code as follows:

function foo () {}
var a = 0;
var b = ' Hush ~ Egg 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 results here will be:

Copy Code code 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. One of the first one may be more familiar with it, C + + inside also have, but uppercase, its essence is a

"" C + +

Define NULL 0

In JavaScript, these three values represent a different meaning.

### NULL ###

Null is a special object, which roughly means empty. For example:

var a = null;
Everyone can understand, do not have more explanations. But unlike C + +, this null is not equal to 0.

### undefined ###

This thing means that this variable is not declared. To be able to better differentiate between null, our sample code is written as follows:

"JavaScript

Copy Code code as follows:

var a = {
' foo ': null
};
Console.log (a["foo"]);
Console.log (a["Bar"]);

In the above code, we let the value of a["foo" be null, or NULL. And there is no statement of a["bar" This thing, it is not even empty. The results of the output should almost have been guessed:

Copy Code code as follows:

Null
Undefined

NaN

This is an empty value and is a special number. Its full name is not a number. It's a bit odd that you can understand that it's not a number-type variable or a numeric error.

More in the case of floating-point numeric arithmetic errors (such as being 0 apart), it can even be that the user makes a variable equal to NaN in order to return an error value so that everyone knows that the function operation is wrong.

Little Bastard.

Other remaining statements are similar to other languages already in existence, such as break, switch, continue and so on.

Variable type

This section is mainly about JavaScript objects, and other types are about the same.

Underlying type

Node.js contains almost as many basic types as the following:

Number
String
Boolean
Array
The first three types can be directly assigned, and the array assignment is just a reference assignment, changing a value in the new variable will change the value of the old variable, you can try the following code directly:

Javascript
var foo = [1, 2, 3];
var bar = foo;
Bar[0] = 3;
Console.log (foo);
The result is:

Javascript
[3, 2, 3]
That is, if the array is to copy a new array, it cannot use the direct assignment method, but must be "deep copy".

It is necessary to talk about the three ways to create an array.

First type:

Javascript

Copy Code code as follows:

var dog = new Array ();
Dog[0] = "Hush ~";
DOG[1] = "egg flower soup";
DOG[2] = "in Sleep";

The second type:

Javascript

Copy Code code as follows:

var dog = new Array ("Hush ~", "Egg flower Soup", "in Bed");

The fourth kind:

Javascript

Copy Code code as follows:

var dog = [
"Hush ~",
"Egg flower Soup",
"In bed."
];

I personally like the third way of writing, relatively concise.

JSON object

Instead of categorizing the JSON object as a JavaScript object, I can simply skip this section if I feel a bit fraught.

My distinction between JSON objects and JavaScript objects is whether they are used only for storing data, not for instantiating a class. In fact, the essence of JSON is the JavaScript Object notation.

For more information about JSON, please do your own encyclopedia.

Declaring a JSON object in Node.js is simple:

Javascript

Copy Code code as follows:

var dog = {
"Pre": "Hush ~",
"Sub": {
"Name": "Egg flower Soup",
"Act": "In Bed",
"Time": 12
},
"Suf": ["I said", "It is Sleeping", "is sleeping"]
};

There are two ways to get the key value of a key in a JSON object, the first is a point connection, and the second is in brackets:

Javascript

Copy Code code as follows:

Dog
. Pre;
dog["Pre"];

Note: The above in the use of the point, the back directly with the key in JSON, if the key as a variable to ask, can only use Dog[key] try: Now you try to see for yourself, with the form of for...in traverse the above JSON object. Don't forget to use the TypeOf Meow ~

The basis of a class (object)

Strictly speaking, the Node.js class is not a class, in fact it is just a collection of functions, plus some member variables. Its essence is actually a function.

But for the sake of speaking, we will call it "class" and instantiate it as "object".

Because the class has a lot of functions, or its essence is a function, so we may be in a inattentive to the function of the base to speak.

Declaration and instantiation of a class

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

Javascript
function foo () {
//...
}
Well, we've already written an Foo class.

Really fake?! It's true.

Don't believe it? Do not believe you can take a piece of code to see:

Javascript
var bar = new Foo ();
Although it is a function, if written in this form (new), it is the instantiation of this class.

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

Member variable

There are two good ways to member variables.

The first is to use the this.< variable name > in the constructor of the class or any constructor. You can declare a member variable at any time, without affecting the use of the outside, anyway, even if it has not been declared, there will be a undefined to hang on. So that's the first way:

Copy Code code as follows:

Javascript
function foo () {
This.hello = "World";
}

Note: It is only when you add this that the member variable of the class is invoked, otherwise it is only a local variable within the function. To be clear about the scope of the variable when there is no this.

The second approach is to declare in the constructor or any member function outside the format of the < class name >.prototype.< variable name:

Javascript

Copy Code code as follows:

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

Whichever of the above is a declaration of a member variable, we can look at the effect:

Javascript

Copy Code code as follows:

var bar = new Foo ();
Console.log (Bar.hello);

You can even modify this class like this:

Javascript

Copy Code code as follows:

function foo () {
This.hello = "World";
}
Foo.prototype.hello = "egg flower soup";

And then use the above code output.

Think about why the world, not the egg soup, is being exported.

Constructors

We talked about this before. Foo () is actually a constructor. So obviously we can pass parameters to the constructor, so we have the following code:

Javascript

Copy Code code as follows:

Code 2.1
function foo (hello) {
if (hello = = undefined) {
This.hello = "World";
} else {
This.hello = Hello;
}
}

We see there is a wonderful judgment on the if (hello = = = undefined), what is the use of this judgment? The first possibility is that the developer is very painful to pass into a undefined, this time it is undefined understandable.

There is also a situation. We started off by saying that JavaScript is a weak type language, but it's not just a weak type, it's passing parameters are very not rigorous. You can do more or less (as long as you can make sure that the program is not wrong, or logic is not wrong), in principle, it is OK. Multiple-pass parameters will be automatically ignored, while the less-transmitted parameters will be undefined to complement.

Take a look at the following code to see:

Javascript

Copy Code code as follows:

Up Code 2.1
var bar1 = new Foo ();
var bar2 = new Foo ("Egg flower soup");

Please output the two bar of the Hello variable, you will find that one is the world one is egg flower soup. Obviously, our first bar1, when declared, was automatically considered by the Node.js:

Javascript

Copy Code code as follows:

var bar1 = new Foo (undefined);

So there it is, the world says.

And in this constructor, we see that the argument passed in is hello and that there is a member variable in this class that is This.hello. But we talked about it before. There is a difference between this and the no, that parameter is only in the constructor, and the one with this is the member variable. Use a this to distinguish them immediately, so it doesn't matter if they have the same name.

member functions

member function declaration

The declaration of a member function is similar to the second declaration method of a member variable, that is, the < class name >.prototype.< function name > = < function >;

Javascript

Copy Code code as follows:

Up Code 2.1
function Sethello (hello) {
This.hello = Hello;
}
Foo.prototype.setHello = Sethello;
Bar1.sethello ("egg cake");

The above code is obvious, we implement the Sethello function of the Foo class, through which we can modify the value of Foo.hello.

But is it a bit of a hassle to write? Next I'm going to talk about the important features of a JavaScript function.

★ Anonymous Function ★

Most of the time some of our functions are referenced or invoked in just one place, so it's not worth it to have a name for the function, so we can write this function temporarily, just let the person referencing it, call it, and call it. So the function can omit the function name, such as:

Javascript

Copy Code code as follows:

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

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

Javascript

Copy Code code as follows:

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

This kind of writing is a result of the declaration of a member function, and it saves a lot of code. In fact, essentially, the declaration of a class member function is declared using this anonymous function.

How do you get anonymous functions to be invoked? This is often used to pass in a function that is called only by a function.

For example, we have a prototype of a function:

Javascript

Copy Code code as follows:

/**
* We'll pass in the A,b two variables,
* After the value of the a+b is calculated, it is referred to Func (num)
* To do the 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 the Chinese output, one is the English output, so if not the anonymous function is so written:

Javascript

Copy Code code as follows:

Function En (A, B, sum) {
The value of Console.log (A + "+" + B +) is: "+ sum";
}
Function En (A, B, sum) {
Console.log (A + "plus" + B + "is" + sum);
}
Sumab (1, 2, en);
Sumab (3, 4, en);

Once the code is executed, the output will be:

The value of 1 + 2 is: 3
3 Plus 4 is 7
Such code, if used in the form of an anonymous function, would be:

Javascript

Copy Code code as follows:

Sumab (1, 2, function (A, b, sum) {
The value of Console.log (A + "+" + B +) is: "+ sum";
});
Sumab (3, 4, function (A, b, sum) {
Console.log (A + "plus" + B + "is" + sum);
});

This form is usually used for the callback function. The callback mechanism is the essence of node.js or JavaScript. In the next chapter will be introduced.

anonymous function declaration method for member function declarations

Although I've talked about it in the last section, I'll say it again.

Normally we declare a member function of a class by using an anonymous function, because that function, which is a member function of the class, will not be referenced or invoked elsewhere, so it has the following code:

Javascript

Copy Code code as follows:

Up Code 2.1
Foo.prototype.setHello = function (hello) {
This.hello = Hello;
}

So we're going to make the Foo class have the Sethello function.

2.3.4 the randomness of the class.

This is my nonsense again. The so-called randomness of class is that you can modify your class anywhere in JavaScript, which is similar to Ruby.

For example, string, which is also a class, with a member variable such as length, there are indexOf, substr and other member functions. But in case we feel that this string is imperfect and wants to add its own method, you can add a function to it where you want it, such as:

Javascript

Copy Code code 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 and make it into SB's avatar.

Let's test this out:

Copy Code code as follows:

var str = "Hush ~ Egg flower soup in bed. ";
Console.log (STR.SB ());

You're going to get this result:

Sbsbsbsbs
You said to your computer, "Hush ~ Egg soup is sleeping." "Your computer will scold you four times and a half fool." (Hit it quickly)

3. Attached

3.1. Deep copy

Deep copy is to create an array or object of your own, manually handcuff the source array or the underlying type variable values in the object, instead of just taking the source array or the object's reference. So this involves a recursive call or something.

Here is a deep copy function that I have implemented, and you can write one of your own and then add it to your own node.js knowledge base.

Javascript

Copy Code code 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;
}

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.