user2160787
user2160787

Reputation: 73

Passing a Javascript-Object to Web Worker

I have an Object like that:

function A(id) {
    this.id = id;
}

A.prototype.getId = function() {
    return this.id;
}

It is included in a html-page as a file ("objects.js") as well as in the web worker with importScript("objects.js"). Now I create an instance of A in the html-page with "var a = new A()" and post it with "postMessage()" to a Web Worker.

The funny thing is that in the worker it still has the property "id" with its value but the prototype function is lost. I guess the reason may be that the prototype functions are "bound" to the html-page context and not to the web worker context.

So what I'm doing in the worker is that:

event.data.a.__proto__ = A.prototype;

It's working and I see it as some kind of cast...

Now my question is if that is the only and a valid way or if there's a better way of posting an object with prototype functions to a web worker. The object definition is available in both contexts...

Upvotes: 7

Views: 5766

Answers (2)

Philipp Claßen
Philipp Claßen

Reputation: 43979

The structure clone algorithm that is used for serializing data before sending it to the web worker does not walk the prototype chain (for details, see § 2.7.5 Safe passing of structured data). That explains why the derived functions are not preserved.

Beside manually restoring the object as you did, you could also creating a new object, which has the prototype functions, and use Object.assign to copy the properties from the received object.

Note that both workarounds assume that the prototype object and their functions are known to the web worker. In general, there is no automated way to transfer arbitrary objects while preserving functions (see my answer to this related question about sending objects with functions).

Upvotes: 4

fredrik
fredrik

Reputation: 6638

The specification for webworkers does not allow for anything but strings to be passed.

Here is a question about this.

So you should serialize the object data with (for example) json and then deserialize it on the other side, and thus creating a new instance of the object, with the same data, inside the webworker.

The same method can be used to pass the object back out again - but both of them must know how to create, serialize and deserialize object of type A.

Upvotes: 0

Related Questions