您可以使用JSON.stringify()
将 JavaScript 普通对象转换为字符串的TextEncoder()
.encode()
方法将字符串转换为 a Uint8Array
,将Uint8Array
.buffer
属性传递给 的第二个参数postMessage()
,然后delete
将原始对象定义为的属性window
或其他对象。
AtWorker
线程使用TextDecoder()
.decode()
方法并JSON.parse()
获取传输的对象。将对象定义为事件Worker
内对象的属性。message
执行将对象转换为字符串和转换为TypedArray
获取属性的相同任务,以将ArrayBuffer
普通对象的表示转移到的属性。.buffer
ArrayBuffer
Window
delete
Worker
在window
this.data = {Cyclic:123,string:"imAString",int:10,Position:{a:1, b:2, c:3}};
const worker = new Worker("worker.js");
const encoder = new TextEncoder();
const decoder = new TextDecoder();
worker.onmessage = e => {
console.log(e.data)
}
console.log("original data in Window:", this.data);
this.encoded = encoder.encode(JSON.stringify(this.data));
worker.postMessage(this.encoded, [this.encoded.buffer]);
delete this.data;
delete this.encoded;
console.log("data deleted in Window:", this.data, this.encoded);
worker.onmessage = e => {
this.data = JSON.parse(decoder.decode(e.data));
console.log("data in message event at window:", this.data);
}
在Worker
const decoder = new TextDecoder();
const encoder = new TextEncoder();
self.onmessage = e => {
console.log(e.data);
self.data = JSON.parse(decoder.decode(e.data));
self.data.string = "imAStringToo";
self.encoded = encoder.encode(JSON.stringify(self.data));
console.log("data in Worker:", self.data);
self.postMessage(self.encoded, [self.encoded.buffer]);
delete self.data;
delete self.encoded;
console.log("data deleted in Worker:", self.data, self.encoded);
}
plnkr http://plnkr.co/edit/my7GS0XRC5iEwjL0I2th?p=preview