如何通过Web-Workers传递自定义类实例? [英] How to pass custom class instances through Web-Workers?

查看:134
本文介绍了如何通过Web-Workers传递自定义类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Web-Worker JSON在线程之间序列化数据,这样的东西不起作用:

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!')

结果会是一个简单的对象,丢失了 foobar 原型方法。

The outcome would be a simple object with the loss of the foobar prototype method.

是否可以将自定义对象传回到主线程而不会失去原型方法?比如,这可以用 ArrayBuffer 吗?我不熟悉那些东西,所以我有点迷失。

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.

推荐答案


  1. 假设您可以编写客户端和Web服务,您可以在两侧定义Animal函数

  2. 然后您可以添加到Animal.prototype(两侧) toJson 方法传递重新创建所需的信息对象(可以选择一些属性来定义className)

  3. 你定义一个使用反向过程的reviver

  4. 然后当你发布时你必须总是JSON.stringify(e)

  5. 在onmessage中你JSON.parse(m,reviver)

  1. Assuming you program both the client and the webservice you can define the Animal function in boths sides
  2. Then you can add to Animal.prototype (in both sides) toJson method to pass the info you need to recreate the object (and may be choose some attribute to define the className)
  3. You define a reviver that use the reverse process
  4. Then when you post you must always JSON.stringify(e)
  5. 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);
}


这篇关于如何通过Web-Workers传递自定义类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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