Search code examples
javascriptweb-workerpostmessage

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...


Solution

  • 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.