This is the first day of my August challenge

  • Let’s start with a MessageChannel

define

The **MessageChannel** interface of the Channel Messaging API allows us to create a new MessageChannel and send data through its two MessagePort properties.

attribute

MessageChannel.port1

Return port1 for channel

MessageChannel.port2

Return channel’s port2

The constructor

  • new MessageChannel()

const { port1, port2 } = new MessageChannel()

Message communication

In simple terms, MessageChannel creates a communication pipe with two ports, each of which can send data via postMessage, and one port can receive data from the other as long as it is bound to the onMessage callback method. A simple example

const { port1, port2 } = new MessageChannel(); Port1. onMessage = function(event) {console.log("port1 received data from port2: "+ event.data); } port2.onmessage = function(event) {console.log("port2 received data from port1: "+ event.data); } port1.postmessage (" send to port2"); Port2. postMessage(" send to port1");Copy the code

Implementing deep copy

Parse (json.stringify (object)) is commonly used to implement deep copy, but this approach has limitations:

  • Ignores undefined
  • Ignore the symbol
  • Non-serializable function
  • Cannot resolve object referenced by loop

If the object you need to copy has built-in types and no functions, use MessageChannel

function structuralClone(obj) { return new Promise(resolve => { const { port1, port2 } = new MessageChannel() port2.onmessage = ev => resolve(ev.data) port1.postMessage(obj) }) } var obj = { a: 1, b: { c: 2}} obj.b.d = obj.b const test = async () => {const clone = await structuralClone(obj) console.log(clone) } test()Copy the code