Basic concepts of JavaScript kernel-basics

Source: Internet
Author: User
Tags numeric value
This chapter focuses on data types (basic types and reference types) in JavaScript, variables (including the scope of variables), operators (primarily some of the more common but not easily understood operators). Because of the "all objects" in JavaScript, after mastering these basic concepts, readers can easily understand concepts such as scopes, calling objects, closures, currying, and so on, which are difficult to understand.

data type

Readers with programming experience must know that in languages such as C or Java, data is typed, such as the attribute used to represent the user name is a string, and the age of an employee is a number, which means that the data model of a switch button on the UI is a Boolean value, and so on, and the number may be subdivided into floating-point numbers, Integer, the integer may be divided into long and short integers, in short, they all represent the type of value of the data in the language.

There are two kinds of data types in javascript: The basic data type and the object type, where the object type contains objects, arrays, and functions (in fact, functions, arrays, and so on are also objects, which are detailed in the following chapters).

1.1.1 Basic Data type

In JavaScript, there are three basic data types, strings (string), numeric values (number), Boolean values (Boolean), and here are some simple examples:

Copy Code code as follows:
var str = "Hello, world";//String
var i = 10;//integer number
var f = 2.3;//floating-point number

var B = true;//Boolean value

We can view the values of variables and the types of variables individually:
Copy Code code 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, and typically, at the client, the programmer uses alert () for similar actions, alert () is the top-level object of the JavaScript interpreter in the browser ( window) is a method.

Hello, World
10
2.3
True

String
Number
Number
Boolean
In JavaScript, all numbers, regardless of integer floating-point, belong to the "number" base type. typeof is a unary operator, which is specifically described in another section of this chapter.

1.1.2 Object Type

The object mentioned here is not the object itself, but a type, which we will discuss in detail in chapter three, where objects include objects (a collection of attributes, a hash of key values), an array (an ordered list), a function (containing executable code).

An object type is a composite data type whose basic elements are composed of basic data types, certainly not limited to basic types, such as the value in an object type can be an instance of another object type, as we illustrate by example:

Copy Code code 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, objects have attributes such as OBJ.STR, Obj.num, the values of these properties can be basic types, and in fact can be more complex, let's look at their types:
Copy Code code as follows:

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

Will print out
Object
Object
function

The reader may be surprised to print an object on the typeof array, in fact, the bounds of objects and arrays are not so obvious (in fact they are of the same type), but their behavior is very different, and the following chapters of this book describe two important data types separately.

2.1.3 Conversion between the two

Similar to the Java Basic data type of automatic boxing unboxing, JavaScript also has a similar action, the basic data type in doing some operations, will temporarily wrap an object, after the operation, and automatically release the object. We can use a few examples to illustrate:

Copy Code code as follows:
var str = "JavaScript kernal";
Print (str.length);//Printing 17

STR is a string that is known by the TypeOf operator as "string" and:

Copy Code code as follows:
var str2 = new String ("JavaScript kernal");
Print (typeof str2);

The STR2 type is "Object", that is, the two are not the same, so why is it possible to use str.length to the length of STR? In fact, When using Str.length, JavaScript automatically wraps a temporary string object with the contents of STR, gets the length property of the object, and finally, the temporary object is freed.

Converting an object to a base type is done by invoking the object's valueof () method to get the value of the object, or using the value if it matches the context's type. If valueof cannot get a value, the object's ToString () method needs to be invoked, and if the context is numeric, the string needs to be converted to a numeric value. Because JavaScript is weakly typed, JavaScript engines need to "guess" the type of object based on context, which makes JavaScript less efficient than a compiled language.

The role of valueof () is to convert the value of an object into a basic type that conforms to the context requirement, and toString () is a veritable print of the object's corresponding string, assuming that you have "overloaded" the object's ToString () method.

In fact, this conversion rule causes a lot of problems, for example, all Non-null objects are converted to true in a Boolean environment, such as:
Copy Code code as follows:

function Converttest () {
if (new Boolean (false) && new Object () &&
New String ("") && new Array ()) {
Print ("Convert to Boolean")
}
}
Converttest ();//convert to Boolean

Beginners are apt to be confused by the type-conversion rules in JavaScript, and in many cases they will find it very awkward to look at, in fact, just have to master the rules, these strange writing will greatly improve the performance of the code, we learn these rules by example:
Copy Code code as follows:

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

print (y);
Print (z);

You can usually find such code in the JS code:

Copy Code code as follows:
if (Datamodel.item) {
Do something ...
}else{
Datamodel.item = new Item ();
}

This type of writing actually has a deeper meaning:

It should be noted that Datamodel.item is an object (string, number, etc.), and if it requires a Boolean expression, a type conversion is done 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 Non-null, the conversion is true, or false. So we can take this shorthand form.

In traditional programming languages (strongly typed), we need to:

Copy Code code as follows:
if (Datamodel.item!= null) {
Do something ...
}else{
Datamodel.item = new Item ();
}


judgement of the type of 2.1.4

When we talked about JavaScript features, we said that JavaScript is a weakly typed language, but sometimes we need to know the type of variable at run time, for example, the argument of a function is expected to be another function:

Copy Code code as follows:
function handlemessage (message, handle) {
return handle (message);
}

The JavaScript engine complains when the function that calls the Handlemessage passes handle is not a function, so it is necessary to make a judgment before the call:

Copy Code code as follows:
function handlemessage (message, handle) {
if (typeof handle = = "function") {
return handle (message);
}else{
throw new Error ("the 2nd argument should be a function");
}
}

However, TypeOf is not always effective, as in the following cases:

Copy Code code as follows:
var obj = {};
var array = ["One", "two", "three", "four"];

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

The running results show that the typeof value of object obj and array arrays is "object" so that we cannot judge it accurately, and then we can make further judgments by calling Instanceof:

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 and the instanceof operator to judge.

2.2 Variables

Variable, that is, by a name to associate a value, you can later refer to the value of the variable, such as:

Copy Code code as follows:
var str = "Hello, world";
var num = 2.345;

The next time we want to refer to the "Hello, Wrold" string for an operation, we just need to use variable str, and 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 types and reference types

In the previous section, we introduced the data types in JavaScript, where basic types such as numbers, Boolean values, which have a fixed size in memory, we use variables to directly access the basic type of data. For reference types, such as objects, arrays, and functions, because their size is not limited in principle, we access them by reference to the reference itself, which is an address that points to the location of the real store of complex objects.

The difference between the basic type and the reference type is obvious, so let's look at a few examples:

Copy Code code as follows:
var x = 1;//digit x, basic type
var y = x;//number y, basic type
print (x);
print (y);

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

print (x);//x value becomes 2
print (y);//y value does not change

The results of the operation are as follows:

1

1

2

1

The results of this operation should be in your expectation, nothing special, let's take a look at the reference type example, because the length of the array is not fixed, can be dynamically added and deleted, so the array is a reference type:

Copy Code code as follows:
var array = [1,2,3,4,5];
var arrayref = array;

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

A reference is to an address, that is, the reference does not point to the reference itself, but to the actual object that the reference corresponds to. So by modifying the array that the array points to, arrayref points to the same object, so the effect is as follows:

1,2,3,4,5,6

Scope of 2.2.2 Variables

A variable is defined as its scope, the global variable has global scope, and local variables, such as variables declared inside the function, have local scopes that cannot be accessed directly from the outside of the function. Like what:

Copy Code code as follows:
var variable = "Out";

function func () {
var variable = "in";
print (variable);//Printing "in"
}

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

It should be noted that the VAR keyword is required in a function, and if you use a variable without writing the var keyword, the default action is on the global object, such as:

Copy Code code as follows:
var variable = "Out";

function func () {
variable = "in";//Note that there is no var keyword before this variable
print (variable);
}

Func ();
print (variable);//global variable variable modified

Because variable is used in the function func without the keyword VAR, the default is the action on the Global object variable property (modifying the variable value in), so this code prints:

In

In



2.3 operator

Operators, usually an easily overlooked content, but some of the more bizarre syntax may still need to use the operator's binding rate or its role to explain, JavaScript, operators must be noted, there are many people with JS programming experience is still unavoidable to be confused.

In this section we mainly explain the following operators:

2.3.1 bracket operator ([])

The [] operator can be used on array objects and objects, and subscript values from the array:

Copy Code code as follows:
var array = ["One", "two", "three", "four"];
ARRAY[0]

And [] can also act on the object, in general, the value of the property in the object is through dots (.) operator to take a value, such as:

Copy Code code as follows:
var object = {
Field: "Self",
Printinfo:function () {
Print (This.field);
}
}

Object.field;
Object.printinfo ();

But given such a situation, when we traverse an object, we know nothing about the key of the property, how do we get through the dots (.) To visit? At this time we can use the [] operator:

Copy Code code as follows:
for (var key in object) {
Print (Key + ":" + Object[key]);
}

The results of the operation are as follows:

Field:slef
Printinfo:function () {
Print (This.field);
}
2.3.2-point operator (.)

The left side of the dot operator is an object (a collection of properties), and the right is the property name, and it should be noted that the right side value is an object other than the property of the object on the left, and possibly its own value to the right:

Copy Code code 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 is the object's property and also the Printinnertext ().

2.3.3 = = and = = and!= and!==

operator = = Read equal, while operator = = is read as equals. Both operators are often seen in JavaScript code, but the meaning is not exactly the same, in short, the equality operator does a type conversion to the operands on both sides, but the equivalence does not. We also illustrate by example:

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

Print (null = = undefined);
Print (null = = undefined);
The results of the operation are as follows:

Copy Code code as follows:
True
False
True
False
True
False

The rules for equality and equivalent operators are as follows:

Equality operator

If the operands have the same type, the equivalence is judged and true (equal) if the values of the two operands are equal, or false (not equal).

If the operands are of different types, it is judged by the following:

null and undefined equal

One is a number and the other is a string, then converts the string to a number and compares

One of these is true, first converted to 1 (false to 0) in comparison

If one value is an object and the other is a number/string, the object is converted to the original value (through ToString () or the valueof () method)

In other cases, return it directly to False

Equivalent operator

If the operand is of a different type, the value is not judged and returned directly to False

If the operands are of the same type, they are judged by the following:

are numbers, and if the values are the same, the two are equal (with one exception, Nan,nan is not equal to itself), otherwise it is not equal

are strings, as in other programming languages, if the value of a string is unequal, it is not equal

are Boolean values, and the values are true/false, equal, otherwise not equal

If two operands refer to the same object (array, function), the two are identical, otherwise they are not equal

If two operands are null/undefined, they are equal, otherwise they are not equal

Like what:

Copy Code code 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:

Copy Code code as follows:
var obj1 = {
ID: "Self",
Name: "Object",
Tostring:function () {
Return "Object 1";
}
}

var obj2 = "Object 1";

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

The return value is:

True

False

Obj1 is an object, and Obj2 is a completely different string, and if judged by the equality operator, the two are exactly the same, because Obj1 overloads the ToString () method of the top-level object.

and!= unequal and!== not equal, then and ==/!== opposite. Therefore, in JavaScript, the use of equality/equivalence, unequal/unequal, must pay attention to the type of conversion, here is recommended to use the same/unequal to judge, so you can avoid some difficult to debug bugs.
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.