[英]Transferable custom classes with ES6 web workers
在Javascript ES6中,在浏览器中,我想使用“Transferable”界面将自定义类对象传输给Web worker。 这可能吗? 我可以找到有关ArrayBuffer对象的文档,但不能找到自定义类对象的文档。
这与如何通过Web-Workers传递自定义类实例不重复? 因为我的问题是关于Transferable接口的。 我想将自定义类实例传递给worker而不复制它。
我已经用不同的方式几次解决了这个问题。 对不起,但是你对这个问题的特定版本的答案绝对没有 。
这有几个原因。
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.