簡體   English   中英

可轉換的自定義類與ES6 Web工作者

[英]Transferable custom classes with ES6 web workers

在Javascript ES6中,在瀏覽器中,我想使用“Transferable”界面將自定義類對象傳輸給Web worker。 這可能嗎? 我可以找到有關ArrayBuffer對象的文檔,但不能找到自定義類對象的文檔。

這與如何通過Web-Workers傳遞自定義類實例不重復 因為我的問題是關於Transferable接口的。 我想將自定義類實例傳遞給worker而不復制它。

我已經用不同的方式幾次解決了這個問題。 對不起,但是你對這個問題的特定版本的答案絕對沒有

這有幾個原因。

  1. 單個JavaScript對象通常不會分配在連續的內存塊上(至少可以在理論上傳輸它們)。
  2. 將普通對象/類轉換為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;
    }
}

它的屬性存儲在數組緩沖區中,您可以將其傳輸。 但它還沒有多少用處,因為它運行良好,我們需要確保它可以從接收到的數組緩沖區構建。 這可以肯定:

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;
    }
}

現在你甚至可以通過從子類傳遞更大的數組緩沖區來子類化它,父類和子元素的屬性都適合:

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;
  }
}

一個簡單的測試:

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));

要真正使用它,您需要解決許多其他問題,並基本上為復雜對象實現自己的內存分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM