JavaScriptではオブジェクトの型を判定するために4つの方法が用意されている。
元となるコンストラクタを取得する「constructor」プロパティ
1 2 3 4 5 6 7 8 9 |
var Animal = function(){}; var Dog = function() {}; Dog.prototype = new Animal(); var a = new Animal(); var d = new Dog(); console.log(a.constructor === Animal); //true console.log(d.constructor === Animal); //true console.log(d.constructor === Dog); //false |
ただし、例のようにプロトタイプを継承している場合は、基底クラスのコンストラクタが取得されてしまうので注意。
instancsof演算子
instanceof演算子はそのオブジェクトが特定のコンストラクタから生成されたかを判定できる。
constructorプロパティと異なり、スーパークラスまでさかのぼって判定することが可能。
1 2 3 4 5 6 7 8 |
var Animal = function(){}; var Dog = function() {}; Dog.prototype = new Animal(); var a = new Animal(); var d = new Dog(); console.log(d instanceof Animal); //true console.log(d instanceof Dog); //true |
isPrototypeOfメソッド
isPrototypeOfメソッドでは、そのインスタンスが特定のプロトタイプを参照しているかを検証することができる。
1 2 3 4 5 6 7 8 9 |
var Animal = function(){}; var Dog = function() {}; Dog.prototype = new Animal(); var a = new Animal(); var d = new Dog(); console.log(Dog.prototype.isPrototypeOf(d)); //true console.log(Animal.prototype.isPrototypeOf(d)); //true console.log(Dog.prototype.isPrototypeOf(a)); //false(aはDogプロトタイプを継承していない) |
in演算子
in演算子はメンバーの有無を判定する。
1 2 3 4 |
var Dog = { bark : function() {} , walk : function() {} }; console.log('bark' in Dog); //true console.log('stand' in Dog); //false |