Determining if an object is a Map in JavaScript

I am writing a function that returns true if the argument passed to it is an instance of the JavaScript Map .

As you might have guessed, typeof new Map() returns the string object , and we don't get the convenient Map.isMap method.

Here is what I still have:

 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}<br />`); } 

So far, so good, but when testing cards between frames and when toString() was overridden, isMap fails ( I understand why ).

Example:

 <iframe id="testFrame"></iframe> <script> const testWindow = document.querySelector('#testFrame').contentWindow; // false when toString is overridden write(isMap(new testWindow.Map())); </script> 

Here is the full Pen code demonstrating the problem

Is there a way to write the isMap function isMap that it isMap true when both toString overridden and the map object comes from a different frame?

+5
source share
1 answer

You can check Object.prototype.toString.call(new testWindow.Map) .

If this has been overridden, you are probably out of luck.

+2
source

Source: https://habr.com/ru/post/1257973/


All Articles