从网络工作者发布数据后参考 [英] Reference after posting data from web worker

查看:29
本文介绍了从网络工作者发布数据后参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为您使用来自网络工作者的postMessage"发送的对象的序列化是使用 JSON.serialize 进行的,而反序列化是使用 JSON.parse 进行的.但是我使用该工作代码进行了测试(在 Firefox 中):

I thought that the serialisation of objects you send with 'postMessage' from a web worker is made with JSON.serialize and the deserialisation with JSON.parse. But I made a test (in Firefox) with that worker code:

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 时没有参考......那么序列化是如何进行的呢?我可以假设在所有浏览器中都有该引用吗?谢谢!

The thing is that the value in a1.save.id is also 7 after that. So there must be a reference but when you use JSON.serialze and JSON.parse there is no reference... So how is the serialisation made? Can I assume that reference in all Browsers? Thanks!

推荐答案

不,Worker 通信不使用 JSON 进行序列化.您可以手动执行并传递字符串,但您不需要这样做.

No, Worker communication does not use JSON for serialisation. You could do manually and pass strings, but you don't need to.

MDN 状态:

在主页和工作人员之间传递的消息是复制的,而不是共享的.对象在交给工作人员时被序列化,然后在另一端反序列化.页面和工作线程不共享同一个实例,因此最终结果是在每一端都创建了一个副本.大多数浏览器将此功能实现为结构化克隆.

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.

事实上,postMessage 的工作规范 表示参数被传递给底层 MessagePortpostMessage指定使用结构化克隆算法 message 参数.

In fact, the Worker spec for postMessage says that the arguments are passed to the underlying MessagePort's postMessage, and that one is specified to use the structured cloning algorithm on the message argument.

这篇关于从网络工作者发布数据后参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆