javascriptinstanceofarraybuffertypedarray

Check for an instance of ArrayBufferView?


Background

With a bit of research I've found that, although ArrayBufferView wasn't initially exposed (through [NoInterfaceObject]) there appeared to be broad agreement that it should be, due to my described use case.

The initial agreement was to expose the ArrayBufferView constructor on the DOMWindow namespace, which was implemented in Safari (and still works in 6.1.1) and Chrome, but was then pulled from Chrome in favour of a static method ArrayBuffer.isView().

Meanwhile, Mozilla are (still) talking about implementing ArrayBuffer.isView().

In brief:

Question

So, my question. What's the most succinct way to check if an object is an instance of ArrayBufferView?


Solution

  • I would use either:

    function isAbv(value) {
        return value && value.buffer instanceof ArrayBuffer && value.byteLength !== undefined;
    }
    

    or:

    var ArrayBufferView = Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;
    function isAbv(value) {
        return value instanceof ArrayBufferView;
    }