Home > Web Front-end > JS Tutorial > body text

Basic concepts of JavaScript kernel_Basic knowledge

WBOY
Release: 2016-05-16 18:00:51
Original
1066 people have browsed it

This chapter mainly talks about data types (basic types and reference types), variables (including the scope of variables), and operators (mainly some common operators that are not easy to understand literally) in JavaScript. Since "everything is an object" in JavaScript, after mastering these basic concepts, readers can easily understand more difficult concepts such as scope, calling objects, closures, currying, etc.

Data type

Readers with programming experience must know that in languages ​​like C or Java, data is typed, for example, it is used to represent user names. The attribute is a string, and the age of an employee is a number. The data model representing a switch button on the UI is a Boolean value, etc. Numbers may also be subdivided into floating point numbers, integers, and integers. Numbers may be divided into long and short integer types. In short, they all represent the value type of data in the language.

Data types in JavaScript are divided into two types: basic data types and object types. Object types include objects, arrays, and functions (in fact, functions, arrays, etc. are also objects, which will be discussed later. Chapter details).

1.1.1 Basic data types

In JavaScript, there are three basic data types, String, Number, and Boolean ( boolean), here are some simple examples:

Copy code The code is as follows:
var str = "Hello, world";//String
var i = 10;//Integer
var f = 2.3;//Floating point

var b = true;//Boolean Value

We can view the value of the variable and the type of the variable respectively:
Copy code 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 that of the rhino interpreter The methods of the top-level object can be used to print strings. Usually, on the client side, programmers often use alert() to perform similar actions. alert() is a top-level object (window) of the JavaScript interpreter in the browser. method.

Hello, world
10
2.3
true

string
number
number
Boolean
In JavaScript, all numbers , whether it is an integer floating point, it belongs to the "number" basic type. typeof is a unary operator, which will be discussed in another section of this chapter.

1.1.2 Object type

The object mentioned here is not the object itself, but a type. We will discuss the object in detail in Chapter 3 Discussion, the objects here include objects (a collection of attributes, that is, a hash table of key values), arrays (ordered lists), and functions (containing executable code).

The object type is a composite data type. Its basic elements are composed of basic data types. Of course, they are not limited to basic types. For example, the values ​​in the object type can be other object type instances. Let’s illustrate with examples. :

Copy code 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, the object has attributes, such as obj. str, 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:
Copy code The code is as follows:

print(typeof obj);
print(typeof array);
print(typeof func);

// Will print out
object
object
function

Readers may be surprised that print(typeof array) prints out object. In fact, the boundaries between objects and arrays are not that Obviously (in fact they are of the same type), but their behavior is very different. The subsequent chapters of this book will introduce the two important data types separately.

2.1.3 Conversion between the two

is similar to the automatic boxing and unboxing of basic data types in Java. JavaScript also has similar actions for basic data types. When doing some operations, an object will be temporarily wrapped, and after the operation is completed, the object will be automatically released. We can illustrate with several examples:

Copy code The code is as follows:
var str = "JavaScript Kernal";
print(str.length);//Print 17

str is a string. Through the typeof operator, we can know that its type is "string", and :

Copy code The code is as follows:
var str2 = new String("JavaScript Kernal") ;
print(typeof str2);

It can be seen that the type of str2 is "object", that is, the two are not the same, so why can we use str.length to get the length of str? Facts Above, when str.length is used, JavaScript will automatically wrap a temporary String object with the content of str, then obtain the length property of the object, and finally, the temporary object will be released.

The object is converted to a basic type in this way: the value of the object is obtained by calling the valueOf() method of the object. If it matches the type of the context, the value is used. If valueOf cannot obtain a value, you need to call the object's toString() method, and if the context is numeric, you need to convert the string into a numeric value. Since JavaScript is weakly typed, the JavaScript engine needs to "guess" the type of the object based on the context, which makes JavaScript less efficient than compiled languages.

The function of valueOf() is to convert the value of an object into a basic type that meets the contextual requirements. toString() is true to its name and can print out the string corresponding to the object. Of course, the premise is that you have "re- "Contains" the toString() method of 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, such as:
Copy code 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 will feel that the writing method looks very awkward. In fact, as long as you master the rules, these weird writing methods will greatly improve the code. Performance, we learn these rules through examples:
Copy code The code is as follows:

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

print(y);
print (z);

You can usually find code like this in JS code:

Copy code The code is as follows:
if(datamodel.item){
//do something...
}else{
datamodel.item = new Item();
}

This way of 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 formula, so type conversion is performed here. In JavaScript, if the context requires a boolean value, the engine automatically converts the object to boolean. The conversion rule is that if the object is not empty, it is converted to true, otherwise it is false. So we can take this abbreviated form.

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

Copy code The code is as follows:
if(datamodel.item != null){
//do something...
}else{
datamodel.item = new Item();
}


2.1.4 Type Judgment

When talking about JavaScript features earlier, we said that JavaScript is a weakly typed language, but Sometimes we need to know the type of a variable at runtime, for example, a function parameter is expected to be another function:

Copy code The code is as follows:
function handleMessage(message, handle){
return handle(message);
}

When the handle passed by the function calling handleMessage is not a function, then The JavaScript engine will report an error, so we need to make a judgment before calling:

Copy the code The code is 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 valid, such as the following situation:

Copy code The code is 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 of object obj and array array The values ​​are all "object", so we cannot judge accurately. At this time, we can make further judgment 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 instanceof operator for judgment.

2.2 Variable

Variable, that is, a value is associated with a name, and the value can be referenced through the variable in the future, such as:

Copy code The code is as follows:
var str = "Hello, World";
var num = 2.345;

The next time we want to refer to the string "Hello, Wrold" to perform a certain operation, we only need to use the variable str. Similarly, we can use 10*num to represent 10*2.345. The purpose of a variable is to "store" the value in the variable.

2.2.1 Basic types and reference types

In the previous section, we introduced the data types in JavaScript. Basic types such as numbers and Boolean values ​​are fixed in memory. The size, we directly access the basic type of data through variables. For reference types, such as objects, arrays and functions, since their sizes are not subject to any restrictions in principle, we access them by accessing their references. The reference itself is an address, which points to the real storage complex. The location of the object.

The difference between basic types and reference types is relatively obvious. Let’s look at a few examples:

Copy codeThe code is as follows:
var x = 1;//Number x, basic type
var y = x;//Number y, basic type
print(x);
print(y);

x = 2;//Modify the value of x

print(x);//The value of x becomes 2
print(y);/ The value of /y will not change

The running results are as follows:

1

1

2

1

Such an operation result should be within your expectations. There is nothing special. Let’s take a look at the example of a reference type. Since the length of the array is not fixed and can be dynamically added or deleted, the array is a reference type:

Copy code 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, Instead, it points to the actual object corresponding to the reference. Therefore, by modifying the array pointed to by array, arrayRef points to the same object, so the operating effect is as follows:

1,2,3,4,5,6

2.2.2 Variables Scope

The area where a variable is defined is its scope. Global variables have global scope; local variables, such as variables declared inside a function, have local scope and cannot be directly accessed outside the function. of. For example:

Copy code 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 necessary within the function. If a variable is used without writing the var keyword, the default operation is to the global object For example:

Copy code 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 variable is modified

Since variable is used in the function func without the keyword var, the default is to operate on the variable attribute of the global object (modifying the value of the variable to in), so this code will print:

in

in



2.3 Operators

operators are usually easily overlooked, but there are some weird ones Grammatical phenomena may still need to be explained by the combination rate or function of operators. In JavaScript, operators are something that must be paid attention to. Many people with JS programming experience are still inevitably confused.

In this section we mainly explain the following operators:

2.3.1 Square bracket operator ([])

[] operator can be used on array objects and object, get the value from the array by subscript:

Copy the code The code is as follows:
var array = ["one", "two", "three", "four"];
array[0]

And [] can also act on objects. Generally speaking, in objects The value of the attribute is obtained through the dot (.) operator, such as:

Copy code The code is as follows:
var object = {
field : "self",
printInfo : function(){
print(this.field);
}
}

object.field;
object.printInfo();

But considering such a situation, when we traverse an object, we have nothing about the keys of the attributes. You know, how do we access through dot (.)? At this time we can use the [] operator:

Copy code The code is as follows:
for(var key in object){
print(key ":" object[key]);
}

The running results are as follows:

field:slef
printInfo:function (){
print(this.field);
}
2.3.2 Dot operator (.)

The left side of the dot operator is an object (a collection of attributes), and the right side is the attribute name. It should be noted that in addition to being an attribute of the object on the left, the value on the right may also be the object of its own value on the right:

Copy code 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 is used as an attribute of object. At the same time, it is the object of printInnerText().

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

The operator == is read as equal and the operator === is read as equal. These two operator operations are often seen in JavaScript code, but their meanings are not exactly the same. In short, the equality operator will perform type conversion on both sides of the operands, while the equality operator will not. Let’s illustrate with examples:

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

print(null == undefined);
print(null === undefined);
The running results are as follows:

Copy code The code is as follows:
true
false
true
false
true
false

The rules for equality and equality operators are as follows:

Equality operator

If the operands have the same type, their equality is judged. If the values ​​of the two operands are equal , then return true (equal), otherwise return false (not equal).

If the types of the operands are different, it will be judged according to this situation:

◆ null and undefined are equal

◆ One of them is a number and the other is a string, then convert the string into a number and compare it

◆ If one of them is true, convert it to 1 first (if false, convert it to 0) Comparing

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

◆ Others case, it will directly return false

Equality operator

If the types of the operands are different, no value judgment will be performed, and false will be returned directly

If the types of the operands are the same , judged according to the following situations:

◆ Both are numbers. If the values ​​are the same, the two are equal (there is an exception, NaN, NaN is not equal to itself), otherwise they are not equal

◆ They are all strings. Like other programming languages, if the values ​​of the strings are not equal, they are not equal, otherwise they are equal.

◆ They are all Boolean values, and the values ​​​​are all true/false , then they are equal, otherwise they are not equal

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

◆ If the two operands refer to the same object (array, function) If both are null/undefined, they are equal, otherwise they are not equal

For example:

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 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);

The return value is :

true

false

obj1 is an object, and obj2 is a string with a completely different structure. If the equality operator is used to judge, the two The two are exactly the same because obj1 overloads the toString() method of the top-level object.

While != is not equal to !==, it is the opposite of ==/!==. Therefore, in JavaScript, when using equality/equity and inequality/not-equal, you must pay attention to type conversion. It is recommended to use equality/not-equal to make judgments, which can avoid some bugs that are difficult to debug.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template