- 相關(guān)推薦
JavaScript instanceof 的使用方法有哪些
在 JavaScript 中,判斷一個(gè)變量的類(lèi)型嘗嘗會(huì )用 typeof 運算符,在使用 typeof 運算符時(shí)采用引用類(lèi)型存儲值會(huì )出現一個(gè)問(wèn)題,無(wú)論引用的是什么類(lèi)型的對象,它都返回 “object”。這就需要用到instanceof來(lái)檢測某個(gè)對象是不是另一個(gè)對象的實(shí)例。
通常來(lái)講,使用 instanceof 就是判斷一個(gè)實(shí)例是否屬于某種類(lèi)型。
另外,更重的一點(diǎn)是 instanceof 可以在繼承關(guān)系中用來(lái)判斷一個(gè)實(shí)例是否屬于它的父類(lèi)型。
復制代碼 代碼如下:
// 判斷 foo 是否是 Foo 類(lèi)的實(shí)例 , 并且是否是其父類(lèi)型的實(shí)例function Aoo(){}
function Foo(){}
Foo.prototype = new Aoo();//JavaScript 原型繼承
var foo = new Foo();
console.log(foo instanceof Foo)//true
console.log(foo instanceof Aoo)//true
上面的代碼中是判斷了一層繼承關(guān)系中的父類(lèi),在多層繼承關(guān)系中,instanceof 運算符同樣適用。
instanceof 復雜用法
復制代碼 代碼如下:
function Cat(){}
Cat.prototype = {}
function Dog(){}
Dog.prototype ={}
var dog1 = new Dog();
alert(dog1 instanceof Dog);//true
alert(dog1 instanceof Object);//true
Dog.prototype = Cat.prototype;
alert(dog1 instanceof Dog);//false
alert(dog1 instanceof Cat);//false
alert(dog1 instanceof Object);//true;
var dog2= new Dog();
alert(dog2 instanceof Dog);//true
alert(dog2 instanceof Cat);//true
alert(dog2 instanceof Object);//true
Dog.prototype = null;
var dog3 = new Dog();
alert(dog3 instanceof Cat);//false
alert(dog3 instanceof Object);//true
alert(dog3 instanceof Dog);//error
要想從根本上了解 instanceof 的奧秘,需要從兩個(gè)方面著(zhù)手:1,語(yǔ)言規范中是如何定義這個(gè)運算符的。2,JavaScript 原型繼承機。大家感興趣的可以去查看相關(guān)資料。
【JavaScript instanceof 的使用方法有哪些】相關(guān)文章:
詳解JavaScript中的splice()使用方法08-20
Javascript中arguments對象的詳解和使用方法08-20
健身器材使用方法有哪些10-04
關(guān)于javascript對象之內置和對象Math的使用方法10-08
對javascript的理解08-08
常用的JavaScript模式09-22
Javascript的this用法簡(jiǎn)述08-15
JavaScript學(xué)習筆記08-24
JavaScript 基礎教學(xué)09-29