javascriptsubclassingtypedarray

Subclassing Uint8Array in Javascript


I try to use Uint8Array to simulate a byte[] or 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.

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.

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.


Solution

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