Check for an instance of ArrayBufferView?

半世苍凉 提交于 2019-12-04 19:31:23

问题


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.

  • Firefox
  • Chrome
  • Safari

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:

  • Safari exposes the ArrayBufferView constructor

  • Chrome has ArrayBuffer.isView()

  • Firefox has nothing

  • IE - I haven't even got near yet...

Question

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


回答1:


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;
}



回答2:


Better answer I guess:

var arr = new Float64Array(100);

arr instanceof (new Uint16Array()).constructor.prototype.__proto__.constructor //true

works in Chrome & Firefox, maybe other browsers too



来源:https://stackoverflow.com/questions/21753581/check-for-an-instance-of-arraybufferview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!