The difference between the value of primitive type and reference type in ECMAScript when copying variable value

1. Copy the value of the basic type variable

   When copying a value of a primitive type from one variable to another, a new value is created on the original variable object and then copied to the location assigned to the new variable.

   Example:

var a1 = 5 ;
var a2 = a1;
alert(a1);     //5
alert(a2);     //5

   In the above code, a1 holds the value 5. When using the value of a1 to initialize a2, 5 is also stored in a2, but the 5 in these two variables (a1, a2) is completely independent, the 5 in a2 is just a copy of the 5 in a1, the two Variables can participate in any operation without affecting each other. The following diagram (Figure 1-1) shows the process of copying the value of a primitive type variable.

                 Figure 1-1 The process of copying the value of a variable of a primitive type 

 

2. Copy the value of a reference type variable       

     When copying a reference type value from one variable to another, it also copies the value stored in the original variable into the space allocated for the new variable. However, the value here is actually a pointer to an object stored on the heap, so both variables will actually refer to the same object. Therefore, changing one of the variables will affect the other.

    Example:

var obj1= new Object();
var obj2= obj1;
obj1.age=5;
alert(obj2.age);   //5

   In the above code, the variable obj1 holds a new instance of an object, and then the value held by obj1 is copied into obj2, which is a pointer to an object; that is, both obj1 and obj2 point to the same object. When the attribute age is added to obj1, this attribute can also be accessed through obj2, because both obj1 and obj2 refer to the same object. The relationship between variables stored in variable objects and objects stored in the heap is shown in Figure 2-1.

   

Figure 2-1 The relationship between variables stored in variable objects and objects stored in the heap

    

   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325285440&siteId=291194637