MessageChannel可以创建一个消息通道
//传递一个字符串
const { port1, port2 } = new MessageChannel();
port1.postMessage('hello')
port2.onmessage = (e) => {
console.log(e.data) // hello
}
//传递一个函数,实现深拷贝
const { port1, port2 } = new MessageChannel();
const obj = {
a: 1,
b: {
c: 2
}
}
port1.postMessage(obj)
port2.onmessage = (e) => {
console.log(e.data) // {a: 1, b: {c: 2}}
console.log(e.data === obj) // false 深拷贝
}
// 封装成一个函数
function deepClone(obj) {
return new Promise(resolve => {
const { port1, port2 } = new MessageChannel();
port1.postMessage(obj);
port2.onmessage = ev => resolve(ev.data);
});
}