Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if an object is a Map in JavaScript [duplicate]

Tags:

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?

like image 237
robbmj Avatar asked Oct 10 '16 15:10

robbmj


1 Answers

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

If that has been overridden, you're probably out of luck.

like image 161
SLaks Avatar answered Sep 30 '22 16:09

SLaks