Reference after posting data from web worker

2019-06-03 04:12发布

问题:

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    
});

Now in the main file you have that:

w.onmessage = function(event) {
    event.data.a2.id = 7;
};

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!

回答1:

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

MDN states:

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.

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.