【发布时间】:2017-02-19 02:23:00
【问题描述】:
如果传递给它的参数是 JavaScript Map 的实例,我正在编写一个返回 true 的函数。
正如您可能已经猜到的那样,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 都被覆盖并且地图对象来自另一个框架时?
【问题讨论】:
标签: javascript instanceof typeof