通常來講,使用 instanceof 就是判斷一個實例是否屬于某種類型。
另外,更重的一點是 instanceof 可以在繼承關系中用來判斷一個實例是否屬于它的父類型。
代碼如下:
// 判斷 foo 是否是 Foo 類的實例 , 并且是否是其父類型的實例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
上面的代碼中是判斷了一層繼承關系中的父類,在多層繼承關系中,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 的奧秘,需要從兩個方面著手:1,語言規范中是如何定義這個運算符的。2,JavaScript 原型繼承機。大家感興趣的可以去查看相關資料。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com