【问题标题】:Subclassing Uint8Array in Javascript在 Javascript 中子类化 Uint8Array
【发布时间】:2020-06-03 07:21:07
【问题描述】:

我尝试使用 Uint8Array 来模拟一个 byte[] 或 uint8[]。

TypedArray.subarray在现有缓冲区上创建新视图,对新对象内容的更改将影响原始对象,反之亦然。

我总是这样使用它:

let u = new Uint8Array(8) //'u' is 8 bytes
let a = u.subarray(4) //'a' is 4 bytes
console.log(a) // show [0,0,0,0], it is ok 

但是当我尝试对 Uint8Array 进行子类化时,子数组变得很奇怪。

class bytes extends Uint8Array {
  constructor(arg) {
    super(arg)
  }
}

let b = new bytes(8) //'b' is 8 bytes
let c = b.subarray(4) //'c' should be 4 bytes, but is 8 bytes
console.log(c) // show [0,0,0,0,0,0,0,0], ??????

我想知道发生了什么以及如何解决它。

【问题讨论】:

  • 有趣...在 Chromium 和 Firefox 上都有。

标签: javascript subclassing typedarray


【解决方案1】:

这与重载的构造函数如何解释参数有关。

这可以正常工作:

class bytes extends Uint8Array {
  constructor(...args) {
    super(...args);
  }
}

let b = new bytes(8);
let c = b.subarray(4);
console.log(c);

【讨论】:

  • constructor(buffer, byteLength, byteOffset) { super(buffer, byteLength, byteOffset);}//没问题
猜你喜欢
  • 2021-05-10
  • 2018-09-27
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2015-02-18
  • 2018-02-19
  • 1970-01-01
  • 2017-09-15
相关资源
最近更新 更多