<分区>
我正在编写一个函数,如果传递给它的参数是 JavaScript 的一个实例,则返回 true
Map .
正如您可能已经猜到的那样,typeof new Map()
返回字符串 object
而我们没有得到方便的 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}<br />`);
}
到目前为止一切顺利,但是当测试帧之间的映射以及覆盖 toString()
时,isMap
失败 (I do understand why)。
例如:
<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
有没有办法编写 isMap
函数,使其返回 true
当 toString
都被覆盖并且 map 对象来自另一个框架时?