instanceof の動き
- カテゴリ:
- JavaScript
- コメント数:
- Comments: 0
◆ X instanceof Y は X.__proto__ === Y.prototype
◆ __proto__ のチェーンもたどるよ
◆ __proto__ のチェーンもたどるよ
instanceof
instanceof では constructor ではなく prototype を見て インスタンスであるかを調べますfunction A(){}
A.prototype = {fn:1}
a = new A
a instanceof A
true
// __proto__を変えると
a.__proto__ = Object.prototype
a instanceof A
false
// 戻す
a.__proto__ = A.prototype
a instanceof A
true
// A.prototypeの方を変えると
A.prototype = {fn2: 2}
a instanceof A
false
なので
X instanceof Y
は
X.__proto__ === Y.prototype
ということになります(基本は)instanceof はプロトタイプチェーンもたどって調べる
// チェーンを辿ってる
function B(){}
b = new B
b instanceof Object
true
// チェーンに適当なオブジェクトを組み込むと
o = {a:10}
function O(){}
O.prototype = o
b.__proto__ = o
b instanceof O
true
なので X instanceof Y は さっきのようなシンプルなものでなく
function instanceof(a, b){
for(var x=a.__proto__;x!=null;x=x.__proto__){
if(x === b.prototype) return true;
}
return false;
}
となります関数内の変数に大文字が気持ち悪かったので a instanceof b と対応してます