我已经多次以不同的方式解决了这个问题。很抱歉,您对本次查询的特定版本的答案肯定是否。
有几个原因。
- 单个 JavaScript 对象通常不会分配在连续的内存块上(这至少在理论上可以传输它们)。
- 任何将普通对象/类转换为
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));
要真正使用它,您需要解决许多其他问题,并从本质上实现您自己的复杂对象的内存分配。