我认为您从 Web Worker 使用“postMessage”发送的对象的序列化是使用 JSON.serialize 进行的,反序列化是使用 JSON.parse 进行的。 但是我用那个工作代码做了一个测试(在 Firefox 中):
function A() {
this.id = 3;
this.save;
}
var a1 = new A();
var a2 = new A();
a1.save = a2;
postMessage({
'a1' : a1,
'a2' : a2
});
现在在主文件中你有:
w.onmessage = function(event) {
event.data.a2.id = 7;
};
问题是 a1.save.id 中的值在那之后也是 7。 所以必须有一个引用,但是当你使用 JSON.serialze 和 JSON.parse 时,没有引用...... 那么连载是如何制作的呢?我可以在所有浏览器中假设该引用吗? 谢谢!
最佳答案
不,Worker 通信不使用 JSON 进行序列化。您可以手动执行并传递字符串,但您不需要这样做。
Messages passed between the main page and workers are copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.
事实上,Worker spec for postMessage
表示参数被传递给底层 MessagePort
的 postMessage
,并且 that one is specified使用 structured cloning algorithm在 message
参数上。
关于javascript - 从 web worker 发布数据后的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414046/