可转换的自定义类与ES6 Web工作者

ato*_*ten 7 web-worker ecmascript-6 transferable

在Javascript ES6中,在浏览器中,我想使用"Transferable"界面将自定义类对象传输给Web worker.这可能吗?我可以找到有关ArrayBuffer对象的文档,但不能找到自定义类对象的文档.

这与如何通过Web-Workers传递自定义类实例不重复因为我的问题是关于Transferable接口的.我想将自定义类实例传递给worker而不复制它.

Tom*_*ica 5

我已经多次以不同的方式解决过这个问题。很抱歉,但您对此查询的特定版本的答案绝对是否定的

这有几个原因。

  1. 单个 JavaScript 对象通常不会分配在连续的内存块上(这至少在理论上可以传输它们)。
  2. 任何将普通对象/类转换为 a 的代码ArrayBuffer实际上只是现有结构化克隆算法的开销,这很好地完成了这项工作。

你可以做什么,

如果你真的想要,我不太确定你应该这样做。

想象一个这样的类:

class Vector2 {
    constructor(existing) {
        this._data = new Float64Array(2);
    }

    get x() {
      return this._data[0];
    }
    set x(x) {
      this._data[0] = x;
    }
    get y() {
      return this._data[1];
    }
    set y(y) {
      this._data[1] = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

它的属性存储在数组缓冲区中,您可以传输它。但这还没有多大用处,要让它运行良好,我们需要确保它可以从接收到的数组缓冲区中构造出来。这肯定可以做到:

class Vector2 {
    constructor(existing) {
        if(existing instanceof ArrayBuffer) {
            this.load(existing);
        }
        else {
            this.init();
        }
    }
    /*
     * Loads from existing buffer
     * @param {ArrayBuffer} existing
    */
    load(existing) {
      this._data = existing;
      this.initProperties();
    }
    init() {
      // 16 bytes, 8 for each Float64
      this._data = new ArrayBuffer(16);
      this.initProperties();
    }
    initProperties() {
      this._coordsView = new Float64Array(this._data, 0, 2);
    }

    get x() {
      return this._coordsView[0];
    }
    set x(x) {
      this._coordsView[0] = x;
    }
    get y() {
      return this._coordsView[1];
    }
    set y(y) {
      this._coordsView[1] = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您甚至可以通过从子类传递更大的数组缓冲区来子类化它,父类和子类的属性都适合:

class Vector2Altitude extends Vector2 {
  constructor(existing) {
    super(existing instanceof ArrayBuffer ? existing : new ArrayBuffer(16 + 8));
    this._altitudeView = new Float64Array(this._data, 16, 1);
  }
  get altitude() {
    return this._altitudeView[0];
  }
  set altitude(alt) {
    this._altitudeView[0] = alt;
  }
}
Run Code Online (Sandbox Code Playgroud)

一个简单的测试:

const test = new Vector2();
console.log(test.x, test.y);
const test2 = new Vector2Altitude();
test2.altitude = 1000;
console.log(test2.x, test2.y, test2.altitude, new Uint8Array(test2._data));
Run Code Online (Sandbox Code Playgroud)

要真正使用它,您需要解决许多其他问题,并实质上为复杂对象实现自己的内存分配。