Understanding of JS Stack and Copy

1. The concept of stack

Stack:
Queue first, first in first out, automatic allocation and release by the operating system, storage function parameter values, local variable values, etc. It operates in a manner similar to a stack in a data structure.
Heap:
In general, the space allocated dynamically is allocated and released by the programmer. If the programmer does not release it, the program may be recovered by OS (Operating System) at the end of the program, which manages and controls the computer hardware and software resources. It is the most basic system software running directly on the bare machine. The allocation method is similar to the linked list.

2. Basic Types and Reference Types

Basic types:
Simple data segments stored in stack memory. The size of data is determined and the size of memory space can be allocated.
Five basic data types: undefined,Null,Boolean,Number and String, which are stored directly by value, so they can be accessed directly.
Reference type:
Objects stored in heap memory, variables actually hold a pointer that points to another location. Each space is different in size and should be allocated according to the situation.
When we need to access the values of reference types (such as objects, arrays, functions, etc.), we first get the address pointer of the object from the stack, and then get the required data from heap memory.

3. Differentiation between Passing Value and Passing Address

Example 1: Create two objects P1 and P2 in js, using assignment method:

  function Person(){//Create a constructor
  this.name = 'zhangsan',
  this.age = 30
}
var p1 = new Person();//Initialize an object, do not need to return this object, automatically return this object
var p2 = p1;//At this point, the address of p1 on the replication heap is given to p2, so now p1 and P2 point to the same memory space on the heap.
console.log(p2.name);//Output zhangsan
p2.name = "apple";//At this point, the property value of the heap object pointed to by the p2 address is modified.
console.log(p1.name);//Output appple
p2 = null;
//console.log(p2.name); error reporting, unable to find the name attribute
console.log(p1.name);//Output apple

Example two:

var a = [1,2,3,4,5]; 
var b =a;//At this point, variables A and B point to objects on the same heap
var c = a[0];
console.log(b);//Eject 1,2,3,4,5
console.log(c);//Pop up 1
b[4] = 6;//Changing stack objects
c = 7;
console.log(a[4]);
console.log(a[0]);

When B data is changed, the data correspondence in a also changes, but when c data is changed, the value of a does not change. This is the difference between value passing and address passing. Because A is an array, it belongs to the reference type, so when it assigns b, it passes the address in the stack (equivalent to a new pointer with different names), not the object in the heap memory. c just takes a data value from a heap memory and saves it on the stack. So when B is modified, it will go back to heap a according to its address, while c is modified directly in the stack, and can not point to heap a memory.

4. shallow copy

In defining an array or object, variables are usually stored in only one address. When we use object copy, if the attribute is an object or an array, then we pass only an address. Therefore, when a child accesses this property, it traces back to the heap memory of the parent object according to its address, which means that the parent and child objects are associated, and their attribute values point to the same memory space.

var a = {
   name : "JavaScript"
}//Create an object using object direct quantities
function Copy(p){
 var c = {};//Create an empty object
 for(var i in p){//for...in traverses all attribute values in the incoming object parameter p
  c[i] = p[i];
  }
  return c;
}
a.author = {
   firstname:"David",
   surname:"Flanagan"
}//Added an attribute to a, which is an object
var b = Copy(a);
b.key3 = '33333';
console.log(b.name);//Enter JavaScript
console.log(b.key3);//Output 33333
console.log(a.key3);//Output undefined 4

A object name is a string, author is an object. When A is copied to b, 1, 2 attributes are copied to B object smoothly, and a string type attribute is added to B object, B can be modified normally, but there is no definition in a, which indicates that the object key3 (basic type) is not related to the parent object, so it is undefined.
however

b.author ={
  name:dadiaoge;
}
console.log(a.author);
console.log(b.author);//Both output changed values

Therefore, when the modified attributes become objects or arrays, the relationship between parent and child objects will occur. That is, when the attributes of b object are modified, the values of author attributes of a and b have changed. Their state in memory can be represented by the following pictures:

name belongs to the basic type, so the data segment is passed in the copy. But the author attribute is an object value, so the author passes the address to the object when it is copied. No matter how many copies of the attribute are copied, the value always points to the memory space of the parent author on the heap.

5. deep copy

In practice, we don't want to associate parent and child objects when encoding. We can use deep copy at this time. Since attribute values are objects or arrays, they will only be addressed. So let's use recursion to solve the problem by traversing all attribute types belonging to objects in all parent objects and assigning them to child objects.

        function Student(){
            this.name = "zhangsan",
            this.age = 12,
            this.grade = {
                English : "good",
                math : "so"
            }

        }
        var a = new Student;//Instantiate an object
        function Copy(p,c){
            var c = c || {};//Create an empty object
            for(i in p){//Attributes in variable p
                if(typeof p[i] === 'object'){//If the type of this property in p is an object
                    c[i] = (p[i].constructor === Array)?[]:{};//Determine whether the type of the attribute is an array type, and return a type after the judgment?
                    Copy(p[i],c[i]);//After the judgment is complete, traverse the property value of p and assign it to the property of the newly created object
                }
                else{
                    c[i] = p[i];
                }
            }
            return c;
        }
        var b = {};
        b = Copy(a,b);
        b.aihao = {
                    English:"great"
        }
        console.log(a);//Do not change the value of its original properties (you can see the whole process for yourself by interrupting points)

The memory process is as follows:

Keywords: Attribute Javascript encoding

Added by ryanthegecko on Fri, 24 May 2019 20:43:53 +0300