确定对象是否是JavaScript中的Map

参见英文答案 > 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).

例如: