参见英文答案 > How to reliably check an object is an EcmaScript 6 Map/Set? 2个
我正在编写一个函数,如果传递给它的参数是JavaScript Map的实例,则返回true.
正如您可能已经猜到的那样,新的Map()会返回字符串对象,并且我们没有得到一个方便的Map.isMap方法.
这是我到目前为止:
function isMap(v) {
return typeof Map !== 'undefined' &&
// gaurd for maps that were created in another window context
Map.prototype.toString.call(v) === '[object Map]' ||
// gaurd against toString being overridden
v instanceof Map;
}
(function test() {
const map = new Map();
write(isMap(map));
Map.prototype.toString = function myToString() {
return 'something else';
};
write(isMap(map));
}());
function write(value) {
document.write(`${value}
到目前为止一切都那么好,但是当测试帧之间的映射并且当覆盖toString()时,isMap失败了(I do understand why).
例如:
Here is a full Code Pen Demonstrating the issue
有没有办法编写isMap函数,以便它返回true
当两个toString被覆盖并且地图对象来自另一个帧时?
最佳答案
您可以检查Object.prototype.toString.call(new testWindow.Map).
如果已被覆盖,那么你可能会失败.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。