[英]Subclassing Uint8Array in Javascript
I try to use Uint8Array to simulate a byte[] or uint8[].我尝试使用 Uint8Array 来模拟 byte[] 或 uint8[]。
TypedArray.subarray creating a new view on the existing buffer,changes to the new object's contents will impact the original object and vice versa. TypedArray.subarray在现有缓冲区上创建一个新视图,对新对象内容的更改将影响原始对象,反之亦然。
I always use it like this:我总是这样使用它:
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
but when I try to subclassing Uint8Array, subarray goes strange.但是当我尝试对 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], ??????
I want to know what happened and how to fix it.我想知道发生了什么以及如何解决它。
It has to do with how arguments are interpreted by the overloaded constructor.它与重载构造函数如何解释参数有关。
This works correctly:这正常工作:
class bytes extends Uint8Array { constructor(...args) { super(...args); } } let b = new bytes(8); let c = b.subarray(4); console.log(c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.