Learning the front end (26) ~ js Learning (IV): the basic data types vs reference data types

In the previous article, we introduced the variables have the following data types:

  • Basic data type (value type): String String, Number values, Boolean Boolean value, Null null, Undefined Undefined.

  • Reference data types (reference type): Object Object.

In this paper, we focused on these two types, for further description. Let's look at an example.

For example the basic data types:

    There are a = 23;
    var b = a;

    a++;

    console.log (a); // print the results: 24
    console.log (b); // print the results: 23

The above code: After a and b are the basic data types, so that b is equal to a, then change the value of a, b and the value found is not changed.

 But in reference data types, different, let's take a look.

Examples reference data types:

    var obj1 = new Object();
    obj1.name = 'smyh';

    // make equal obj1 obj2
    was Obj2 = obj1;

    // change the name attribute of obj1
    obj1.name 'Wo';

    console.log (obj1.name); // print the results: vae
    console.log (obj2.name); // print the results: vae

The above code: after obj1 and obj2 are reference data types, so that equal obj1 obj2, then modify the value obj1.name found obj2.name value is also changed.

From the above example, it can reflect the basic data types and the reference data types are differentiated to.

That in the end what difference does it make? We further look down.

Stack memory and heap memory

We first remember one sentence: in JS, all variables are stored in the stack memory.

Then take a look at the following differences.

Basic data types:

Value of the basic data types, stored directly in the memory stack . Between the value and the value of independent existence, modify a variable does not affect other variables.

Reference data types:

The object is saved to the stack memory . Each create a new object, it will open up a new space in the heap memory, and variable holds the memory address of the object ( object reference ) . If two variables hold the same object reference, when a modified property through a variable, the other will also be affected.

 

Guess you like

Origin www.cnblogs.com/Vincent-yuan/p/12393050.html