JavaScript instanceof 的使用方法有哪些

在 JavaScript 中,判斷一個變量的類型嚐嚐會用 typeof 運算符,在使用 typeof 運算符時採用引用類型存儲值會出現一個問題,無論引用的是什麼類型的對象,它都返回 “object”。這就需要用到instanceof來檢測某個對象是不是另一個對象的.實例。

JavaScript instanceof 的使用方法有哪些

通常來講,使用 instanceof 就是判斷一個實例是否屬於某種類型。

另外,更重的一點是 instanceof 可以在繼承關係中用來判斷一個實例是否屬於它的父類型。

複製代碼 代碼如下:

// 判斷 foo 是否是 Foo 類的實例 , 並且是否是其父類型的實例function Aoo(){}

function Foo(){}

otype = new Aoo();//JavaScript 原型繼承

var foo = new Foo();

(foo instanceof Foo)//true

(foo instanceof Aoo)//true

上面的代碼中是判斷了一層繼承關係中的父類,在多層繼承關係中,instanceof 運算符同樣適用。

instanceof 複雜用法

複製代碼 代碼如下:

function Cat(){}

otype = {}

function Dog(){}

otype ={}

var dog1 = new Dog();

alert(dog1 instanceof Dog);//true

alert(dog1 instanceof Object);//true

otype = otype;

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

otype = null;

var dog3 = new Dog();

alert(dog3 instanceof Cat);//false

alert(dog3 instanceof Object);//true

alert(dog3 instanceof Dog);//error

要想從根本上了解 instanceof 的奧祕,需要從兩個方面着手:1,語言規範中是如何定義這個運算符的。2,JavaScript 原型繼承機。大家感興趣的可以去查看相關資料。