Deep and shallow copy (the method of hanging the interviewer)

deep copy concept

        Shallow copy: copy the address value of the original object and store it in the stack, and point to the original object heap space data

                        The address values ​​of the original object and the copy object point to the same memory space, and have

                        Sharing and Connectivity

        Deep copy: Copy the specific content of the original object, and independently generate an address value in the stack (different from the original object address value), and a new memory space in the heap (same as the original object data) and point to this memory . The original object and the new object have mutual non-interference

shallow copy method

1、Object.asssign(目标对象,新对象)
2、var obj1={}
    for(var key in obj1){
        obj1[key]=obj2[key]
}

3、 var obj={}
    var obj1={...obj}

deep copy method  

        1. Use JSON for deep copy, so this method cannot handle object loop calls (obj.a=obj)

                There is an error

                

 

var obj1={}
var obj2=JSON.pores(JSON.stringify(obj1))

          2. (The method of tearing the interviewer by hand is here) 

                Use the MessageChannel() constructor to solve the situation of object circular calls

                Principle: The MessageChannel() constructor instantiates a Channel object, when the iframe is loaded

                           The MessagePort.Post.Message method will pass a message and MessageChannel.Port2 to the iframe, handleMessage will receive the message and put it in the innerHTML

//此处采用封装
    funtion colne(obj){
        return new Promise(reslove()=>{
             const {port1,port2}= new MessageChannel()
                  port1.postmessage(obj)
                  port2.onmessage=(msg)=>{
                        reslove(msg.data)
    }
})
}

        

Guess you like

Origin blog.csdn.net/qq_59389108/article/details/129250430