I am writing a function that returns true
if the argument passed to it is an instance of a JavaScript Map.
As you may have guessed typeof new Map()
returns the string object
and we don't get a handy Map.isMap
method.
Here is what I have so far:
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 maps between frames and when toString()
has been overridden, isMap
fails (I do understand why).
For 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 a full Code Pen Demonstrating the issue
Is there a way to write the isMap
function so that it will return true
when both toString
is overridden and the map object originates from another frame?
You can check Object.prototype.toString.call(new testWindow.Map)
.
If that has been overridden, you're probably out of luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With