Since Web-Worker JSON serialize data between threads, something like this doesn't work:
worker.js
function Animal() {}
Animal.prototype.foobar = function() {}
self.onmessage = function(e) {
self.postMessage({animal: new Animal()})
}
main.js
let worker = new Worker('worker.js')
worker.onmessage = function(e) {
console.log(e.data)
}
worker.postMessage('go!')
The outcome would be a simple object with the loss of the foobar
prototype method.
Is it possible to transfer the custom object back to the main thread without losing its prototype methods? Like, would this be possible with ArrayBuffer
? I'm not familiar with that stuff, so I'm a bit lost.
In the onmessage you JSON.parse(m,reviver)
function Animal(name, age){
var private_name = name;
this.public_age = age;
this.log = function(){
console.log('Animal', private_name, this.public_age);
}
this.toJson = function(){
return JSON.stringify({
__type__:'Animal', // name of class
__args__:[this.public_age, private_name] // same args that construct
});
}
}
Animal.prototype.age = function(){
return this.public_age;
}
var a = new Animal('boby', 6);
worker.postMessage(JSON.stringify(a));
function reviver(o){
if(o.__type__){
var constructor=reviver.register[o.__type__];
if(!constructor) throw Error('__type__ not recognized');
var newObject = {};
return constructor.apply(newObject, o.__args__);
}
return o;
}
reviver.register={}; // you can register any classes
reviver.register['Animal'] = Animal;
worker.onmessage = function(m){
var a = JSON.parse(e, reviver);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With