JavaScript -- Item4 basic type and basic packaging type that you don't know (reference type)

Source: Internet
Author: User

JavaScript -- Item4 basic type and basic packaging type that you don't know (reference type)
1. Basic and reference types

There are five basic data types:Undefined, boolean, number, string, null

typeof null;   //objecttypeof undefined;  //undefinedtypeof 1;  //numbertypeof false  //booleantypeof 1  //string

(It is confusing that the result of the typeof operation on the null type is "object". However, ECMAScript Standards describe it as a unique type .)

To facilitate the operation of basic type values, ECMAScript also provides three special reference types:Boolean, Number, and StringThe standard library provides constructors to encapsulate boolean values, numbers, and strings as objects. These types are similar to other reference types and have special behaviors corresponding to their basic packaging types. In fact, every time you read a basic type value, the background will create a corresponding BASIC packaging type object, so that we can call some methods to operate on the data.

var s1 = some text;var s2 = s1.substring(2);var s3 = new String(some text);

But unlike the original String, the String object is a real object.

typeof s1;  //stringtypeof s3;  //object

In this example, the variable s1 contains a string, which is of course a basic type value. The next line calls the substring () method of s1 and stores the returned results in s2. We know that basic type values are not objects, So logically, they should not have methods (but they do have methods ). In fact, in order to achieve this intuitive operation, the background has automatically completed a series of processing. When the second line of code accesses s1, the access process is in a read mode, that is, to read the value of this string from the memory. When accessing strings in Read mode, the background will automatically complete the following processing:

(1) Create an instance of the String type.

(2) Call the specified method on the instance.

(3) destroy the instance.

You can use the following code:

var s1 = new String(some text);var s2 = s1.substring(2);s1 = null;

After this processing, the basic string value becomes the same as the object. The preceding three steps also apply to Boolean and Number values corresponding to the Boolean and Number types.

2. Lifecycle

The main difference between the reference type and the basic packaging type is the object lifecycle. Instances of the reference type created using the new operator are stored in the memory until the execution stream leaves the current scope. The automatically created basic packaging type objects only exist in the execution period (instantly) of this line of code, and then are destroyed immediately. This means that we cannot add attributes and methods for attributes at runtime.

var s1 = some text;s1.color = red;alert(s1.color); //undefined

Of course, you can call Boolean, Number, and String to create objects of the basic packaging type. However, this is not recommended. When typeof is called for an instance of the basic packaging type, "object" is returned, and all objects of the basic packaging type are converted to a Boolean value of true ..

var obj = new Object(some text);alert(obj instanceof String) //true

It is worth noting that using new to call constructors of the basic packaging type is different from directly calling transformation functions with the same name.

Var value = 25; var number = Number (value); // transformation function alert (typeof number) // numbervar obj = new Number (var ); // constructor alert (typeof obj) // object
3. Basic Type features

1. The value of the basic type cannot be changed:

No method can change the value of a basic type, such as a string:

Var name = 'job'; name. toUpperCase (); // output 'job' console. log (name); // output 'job'

The original name is not changed, but a new string is returned after the toUpperCase () method is called.
Let's take a look:

var person = 'jozo';person.age = 22;person.method = function(){//...};console.log(person.age); // undefinedconsole.log(person.method); // undefined

The code above shows that we cannot add attributes and methods to the basic type, and cannot change the basic type again;

2. Comparison of basic types is a comparison of values:

They are equal only when their values are equal.
However, you may:

var a = 1;var b = true;console.log(a == b);//true

Are they not equal? In fact, this is the knowledge of type conversion and = Operator. That is to say, some type conversion is performed when two variables of different types are compared with =. As shown in the preceding comparison, true is converted to number 1 and then compared with Number 1. The result is true. This is when the two values of different types are compared, the = Operator will perform type conversion, but when the two values of the same type, even the = Operator is equivalent to =.

var a = 'jozo';var b = 'jozo';console.log(a === b);//true

3. The basic types of variables are stored in the stack (stack refers to the stack memory in the memory)

Suppose there are several basic types of variables:

var name = 'jozo';var city = 'guangzhou';var age = 22;

Then its storage structure is as follows:

The stack includes the variable identifier and variable value. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjxoMiBpZD0 = "4 reference type features"> 4. Reference Type features

The reference type is more fun and interesting.

In javascript, in addition to the above basic types (number, string, boolean, null, undefined), it is the reference type, or object. An object is a set of attributes and methods. That is to say, the reference type can have attributes and methods, and the attributes can also contain basic types and reference types. Let's take a look at some features of the reference type:

1. The value of the reference type is variable.

We can add attributes and methods for reference types, or delete their attributes and methods, such:

Var person = {}; // create a control object -- reference type person. name = 'job'; person. age = 22; person. sayName = function () {console. log (person. name);} person. sayName (); // 'job' delete person. name; // delete the name attribute person of the person object. sayName (); // undefined

The code above demonstrates that the reference type can have attributes and methods and can be dynamically changed.

2. The reference type value is an object stored in both stack memory and heap memory.

Different from other languages, javascript does not allow direct access to locations in the memory. That is to say, it cannot directly operate on the memory space of objects. What should we do? In fact, it is a reference to an operation object, so the value of the reference type is accessed by reference.

To be accurate, the reference type of storage requires the stack and heap areas of the memory (the heap area refers to the heap memory in the memory) to be completed together, the stack memory saves the variable identifier and pointer to the object in the heap memory, which can also be said to be the address of the object in the heap memory.
Suppose there are the following objects:

var person1 = {name:'jozo'};var person2 = {name:'xiaom'};var person3 = {name:'xiaoq'};

The three objects are stored in the memory as follows:

3. Comparison of reference types is a comparison of reference types.

var person1 = '{}';var person2 = '{}';console.log(person1 == person2); // true

The comparison of the basic types mentioned above indicates that when the two comparison values are of the same type, the result is equivalent to =, so the output is true. Let's take a look:

var person1 = {};var person2 = {};console.log(person1 == person2); // false

You may have seen the flaw. The above comparison is two strings, and the following comparison is two objects. Why are the objects with the same length not equal?

Don't forget, access by reference during the reference type. In other words, it is to compare whether the addresses in the heap memory of the two objects are the same. Obviously, the addresses of person1 and person2 are different in the heap memory:

Therefore, these two objects are completely different, so false is returned;

5. Simple assignment

When you assign a basic type value from a variable to another variable, a new value is created in the variable, and then the value is copied to the location assigned to the new variable:

var a = 10;var b = a;a ++ ;console.log(a); // 11console.log(b); // 10

In this case, the value saved in a is 10. When a is used to initialize B, the value saved in B is 10, but 10 in B is completely independent from that in, this value is only a copy of the value in a. Since then, these two variables can participate in any operation without affecting each other.

That is to say, after the value assignment operation, the two variables are mutually unaffected.

6. Object Reference

When a value of the reference type is assigned to another variable, the value of the object stored in the variable is also copied to the space allocated for the new variable. As mentioned above, the address stored in the variable is the address of the object in the heap memory. Therefore, unlike the simple value assignment, the copy of this value is actually a pointer, this pointer points to an object stored in heap memory. After the value assignment operation, both variables store the same object address, and the two variables point to the same object. Therefore, changing any of these variables will affect each other:

Var a = {}; // a saves an empty object instance var B = a; // both a and B point to this empty object. name = 'job'; console. log (. name); // 'job' console. log (B. name); // 'job' B. age = 22; console. log (B. age); // 22console. log (. age); // 22console. log (a = B); // true

Their relationships are as follows:

Therefore, the value assignment of the reference type is actually the value assignment of the address pointer of the object stored in the stack area. Therefore, if two variables direct to the same object, any operation will affect each other.

 

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.