渡された引数がJavaScriptのインスタンスである場合、true
を返す関数を作成しています。Map。オブジェクトがJavaScriptのマップであるかどうかを調べる
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
両方toString
が上書きされ、マップオブジェクトが別のフレームに由来する場合、それはtrue
を返すようisMap
機能を書くための方法はありますか?
@Bergi、これは重複していますか?あなたの答えを支持して 'instanceof'を使用して私の質問は' instanceof'であなたがセットでチェックしている内部メソッドも持っている問題を述べ、 'Map'プロトタイプ(私は思う)には当てはまりません。 – robbmj
これはセットとマップで全く同じです。私は正解になるように答えを編集するほうがいいと思う。 – Bergi
@Bergi上記の編集を私のコメントに見てください。 – robbmj