Basic concepts of JavaScript KERNEL _ basic knowledge

Source: Internet
Author: User
Tags integer numbers
This article will focus on the basic concepts in JavaScript. These concepts are quite different from those in traditional languages. Therefore, we will list a separate chapter for specific descriptions to understand the concepts of this chapter and the concepts of subsequent chapters in this book, code behavior and so on will be of great help, readers may wish to spend a lot of time in this chapter, even if you are familiar with JavaScript, it is also recommended to read through this chapter to focus on the JavaScript data types (Basic Types and reference types), variables (including the scope of variables), operators (mainly common, but not operators that can be understood literally ). Because "Everything is an object" in JavaScript, after understanding these basic concepts, readers can easily understand such as scope, calling objects, and closures, currying and so on.

Data Type

Readers who have experience in programming must know that in a language such as C or Java, data is of a type. For example, the attribute used to indicate the user name is a string, an employee's age is a number, indicating that the data model of a switch button on the UI is a Boolean value, etc. The numbers may be subdivided into floating-point numbers and integer numbers, integer types can be further divided into Long and Short integer types. In short, they all represent the types of data values in the language.

There are two types of data in JavaScript: Basic Data Type and object type. The object type includes objects, arrays, and functions (in fact, functions and arrays are also objects, this is detailed in later chapters ).

1.1.1 Basic Data Types

JavaScript contains three basic data types: String, Number, and boolean. Below are some simple examples:

The Code is as follows:

Var str = "Hello, world"; // string
Var I = 10; // integer
Var f = 2.3; // floating point number

Var B = true; // Boolean Value


We can view the values and types of variables respectively:

The Code is as follows:


Print (str );
Print (I );
Print (f );
Print (B );

Print (typeof str );
Print (typeof I );
Print (typeof f );
Print (typeof B );


Note that the print () function used here is the method of the top-level object of the rhino interpreter, which can be used to print strings. Generally, on the client, programmers usually use alert () for similar actions, alert () is a method of the top-level object (window) of the JavaScript interpreter in the browser.

Hello, world
10
2.3
True

String
Number
Number
Boolean
In JavaScript, all numbers, whether integer floating point, belong to the basic type of "number. Typeof is a one-dimensional operator, which is discussed in another section in this chapter.

1.1.2 object type

The object mentioned here is not an object, but a type. In chapter 3, we will discuss the object in detail. The object here includes the object (set of attributes, hash of key values, arrays (ordered lists), and functions (including executable code ).

An object type is a composite data type. Its basic elements consist of basic data types. Of course, they are not limited to basic types. For example, the value of an object type can be an instance of another object type, we use examples to illustrate:

The Code is as follows:

Var str = "Hello, world ";
Var obj = new Object ();
Obj. str = str;
Obj. num = 2.3;

Var array = new Array ("foo", "bar", "zoo ");

Var func = function (){
Print ("I am a function here ");
}


As you can see, an object has attributes, such as obj. str and obj. num. The values of these attributes can be basic types. In fact, they can be more complex. Let's take a look at their types:

The Code is as follows:


Print (typeof obj );
Print (typeof array );
Print (typeof func );

// Print the output
Object
Object
Function


Readers may wonder how print (typeof array) Prints objects. In fact, the boundaries between objects and arrays are not that obvious (in fact they belong to the same type ), however, their behavior is very different. Two important data types are introduced in the subsequent sections of this book.

2.1.3 conversion between the two

Similar to the automatic packing and unpacking of basic data types in Java, JavaScript also has similar actions. When some operations are performed on basic data types, an object is temporarily packaged. After the calculation, and Automatically releases the object. Here are several examples to illustrate:

The Code is as follows:

Var str = "JavaScript Kernal ";
Print (str. length); // print 17


Str is a string. The typeof operator indicates that its type is "string", while:

The Code is as follows:

Var str2 = new String ("JavaScript Kernal ");
Print (typeof str2 );


We can see that the type of str2 is "object", that is, the two are not the same. Why can we use str. length to get the length of str? In fact, when str. during length, JavaScript automatically wraps a temporary String object whose content is str, obtains the length attribute of the object, and then releases the temporary object.

To convert an object to a basic type, you can call the valueOf () method of the object to obtain the value of the object. If the value matches the context type, the value is used. If valueOf cannot obtain the value, you need to call the toString () method of the object. If the context is numeric, You need to convert the string to a value. Because JavaScript is of a weak type, the JavaScript engine needs to "Guess" the object type based on context, which makes JavaScript more efficient than compiled languages.

ValueOf () is used to convert the value of an object into a basic type that meets the context requirements. toString () is a real name and can print the corresponding string of the object, of course, the premise is that you have "overloaded" The toString () method of the Object.

In fact, this conversion rule will cause many problems. For example, all non-empty objects will be converted to true in a Boolean environment, for example:

The Code is as follows:


Function convertTest (){
If (new Boolean (false) & new Object ()&&
New String ("") & new Array ()){
Print ("convert to boolean ")
}
}
ConvertTest (); // convert to Boolean


Beginners are easily confused by the type conversion rules in JavaScript. In many cases, they may feel that the writing method is very awkward. In fact, they only need to master the rules, these odd writing methods will greatly improve the Code performance. We can use examples to learn these rules:

The Code is as follows:


Var x = 3;
Var y = x + "2"; // => 32
Var z = x + 2; // => 5

Print (y );
Print (z );


The following code can be found in JS Code:

The Code is as follows:

If (datamodel. item ){
// Do something...
} Else {
Datamodel. item = new Item ();
}


This writing actually has a deeper meaning:

It should be noted that datamodel. item is an object (string, number, etc.), and if requires a boolean expression, so type conversion is performed here. In JavaScript, if the context requires a boolean value, the engine automatically converts the object to a boolean type. The conversion rule is: if the object is not empty, convert it to true; otherwise, false. Therefore, we can adopt this short form.

In traditional programming languages (strong types), we need:

The Code is as follows:

If (datamodel. item! = Null ){
// Do something...
} Else {
Datamodel. item = new Item ();
}



2.1.4 type judgment

When talking about the JavaScript feature, we have said that JavaScript is a weak type language, but sometimes we need to know the type of the variable at runtime, for example, the parameter of a function is expected to be another function:

The Code is as follows:

Function handleMessage (message, handle ){
Return handle (message );
}


When handle passed by the handleMessage function is not a function, the JavaScript engine reports an error. Therefore, we need to judge before calling it:

The Code is as follows:

Function handleMessage (message, handle ){
If (typeof handle = "function "){
Return handle (message );
} Else {
Throw new Error ("the 2nd argument shocould be a function ");
}
}


However, typeof is not always valid, for example:

The Code is as follows:

Var obj = {};
Var array = ["one", "two", "three", "four"];

Print (typeof obj); // object
Print (typeof array); // object


The running result shows that the typeof values of object obj and array are "object", so that we cannot accurately judge them. At this time, we can call instanceof for further judgment:

Print (obj instanceof Array); // false
Print (array instanceof Array); // true
The first line of code returns false, and the second line returns true. Therefore, we can combine the typeof operator with the instanceof operator for judgment.

2.2 Variables

Variable, that is, associate a value by a name, and then reference the value through the variable, for example:

The Code is as follows:

Var str = "Hello, World ";
Var num = 2.345;


When we reference the "Hello, Wrold" string next time to perform an operation, we only need to use the variable str. Similarly, we can use 10 * num to represent 10*2.345. The function of a variable is to store the value on this variable.

2.2.1 basic and reference types

In the previous section, we introduced the data types in JavaScript, where the basic types such as numbers and boolean values all have fixed sizes in memory, we use variables to directly access basic types of data. For reference types, such as objects, arrays, and functions, since their sizes are not subject to any restrictions in principle, we can access them through their referenced access, A reference itself is an address that points to the location where a complex object is stored.

The differences between basic and reference types are obvious. Let's look at several examples:

The Code is as follows:

Var x = 1; // number x, basic type
Var y = x; // numeric y, basic type
Print (x );
Print (y );

X = 2; // modify the value of x.

Print (x); // The value of x is 2.
Print (y); // The value of y does not change.


The running result is as follows:

1

1

2

1

There is nothing special about this running result. Let's take a look at the example of the reference type. because the length of the array is not fixed, it can be dynamically added or deleted, so the array is the reference type:

The Code is as follows:

Var array = [1, 2, 3, 4, 5];
Var arrayRef = array;

Array. push (6 );
Print (arrayRef );


The reference points to the address, that is, the reference does not point to the reference itself, but to the actual object corresponding to the reference. Therefore, by modifying the array to which array points, arrayRef points to the same object, so the running effect is as follows:

1, 2, 3, 4, 5, 6

2.2.2 scope of Variables

The region where a variable is defined is its scope. A global variable has a global scope. A local variable, for example, a variable declared within a function has a local scope, you cannot directly access the function outside the function. For example:

The Code is as follows:

Var variable = "out ";

Function func (){
Var variable = "in ";
Print (variable); // print "in"
}

Func ();
Print (variable); // print "out"


It should be noted that the var keyword is required in the function. If the variable is used but the var keyword is not written, the default operation is for the global object, for example:

The Code is as follows:

Var variable = "out ";

Function func (){
Variable = "in"; // note that there is no var keyword before this variable
Print (variable );
}

Func ();
Print (variable); // The global variable is modified.


Because the function func uses variable without the keyword var, the operation is performed on the variable attribute of the global object by default (the value of variable is changed to in). Therefore, this code segment will print:

In

In



2.3 Operator

Operators are usually easy to ignore. However, some odd syntax phenomena may still need to be interpreted by the combination rate or function of operators. In JavaScript, operators are important. Many people with JS programming experience are still confused.

This section describes the following operators:

2.3.1 brackets operator ([])

[] Operators can be used on array objects and objects. values can be subscript-based in the array:

The Code is as follows:

Var array = ["one", "two", "three", "four"];
Array [0]


[] Can also act on objects. Generally, the attribute values in an object are obtained through the vertex (.) operator, for example:

The Code is as follows:

Var object = {
Field: "self ",
PrintInfo: function (){
Print (this. field );
}
}

Object. field;
Object. printInfo ();


However, in this case, when we traverse an object, we have no idea about the key of the attribute. How can we access it through a dot? In this case, we can use the [] OPERATOR:

The Code is as follows:

For (var key in object ){
Print (key + ":" + object [key]);
}


The running result is as follows:

Field: slef
PrintInfo: function (){
Print (this. field );
}
2.3.2 vertex operator (.)

The left side of the vertex operator is an object (set of attributes) and the right side is the attribute name. Note that the value on the right is not only the attribute of the object on the left, it may also be the object of its own right value:

The Code is as follows:

Var object = {
Field: "self ",
PrintInfo: function (){
Print (this. field );
},
Outter :{
Inner: "inner text ",
PrintInnerText: function (){
Print (this. inner );
}
}
}

Object. outter. printInnerText ();


In this example, outter serves as the property of the object and is also an object of printInnerText.

2.3.3 = and! = And! =

Operator = reads are equal, while operator = reads are equal. These two operators are often seen in JavaScript code, but their meanings are not exactly the same. In short, equal operators perform type conversion on the operands on both sides, but equal operators do not. We will illustrate the following through examples:

Print (1 = true );
Print (1 = true );
Print ("" = false );
Print ("" = false );

Print (null = undefined );
Print (null = undefined );
The running result is as follows:

The Code is as follows:

True
False
True
False
True
False


The rules for equal and equal operators are as follows:

Equal Operators

If the operand has the same type, the equivalence is determined. If the two operands have the same value, true (equal) is returned; otherwise, false (not equal) is returned ).

If the type of the operand is different, the result is as follows:

◆ Null and undefined are equal

◆ If one is a number and the other is a string, the string is converted to a number for comparison.

◆ If one of them is true, first convert to 1 (false to 0) before comparison

◆ If one value is an object and the other is a number or string, the object is converted to the original value (using the toString () or valueOf () method)

◆ In other cases, false is directly returned.

Equivalent Operator

If the type of the operand is different, no value is determined and false is returned directly.

If the operands are of the same type, perform the following operations:

◆ It is a number. If the value is the same, the two are the same (except that NaN and NaN are not the same as themselves). Otherwise, they are not the same.

◆ It is a string. It is the same as other programming languages. If the value of a string is different, it is not the same; otherwise, it is equivalent.

◆ All values are boolean values, and the values are true/false. Otherwise, they are not the same.

◆ If the two operands reference the same object (array, function), the two are completely equivalent; otherwise, they are not the same

◆ If both operands are null/undefined, they are equivalent. Otherwise, they are not the same.

For example:

The Code is as follows:

Var obj = {
Id: "self ",
Name: "object"
};

Var oa = obj;
Var ob = obj;

Print (oa = ob );
Print (oa = ob );


Will return:

True

True

Let's look at an example of an object:

The Code is as follows:

Var obj1 = {
Id: "self ",
Name: "object ",
ToString: function (){
Return "object 1 ";
}
}

Var obj2 = "object 1 ";

Print (obj1 = obj2 );
Print (obj1 = obj2 );


Return Value:

True

False

Obj1 is an object, while obj2 is a string with a completely different structure. If we use the equal operator to judge, the two are exactly the same, because obj1 overload the toString () method of the top-level object.

And! = Not equal! =, And = /! = Opposite. Therefore, when using equal/equal, unequal/different types in JavaScript, you must pay attention to the type conversion. Here we recommend that you use the same/different types for determination, this avoids some bugs that are difficult to debug.
Related Article

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.