溫馨提示×

javascript中instanceof運算符怎么使用

小億
105
2023-08-12 02:12:41
欄目: 編程語言

在JavaScript中,instanceof運算符用于檢查一個對象是否是某個構(gòu)造函數(shù)的實例。它的使用方法如下:

object instanceof constructor

其中,object是要檢查的對象,constructor是要檢查的構(gòu)造函數(shù)。如果objectconstructor的實例,則返回true;否則返回false。

例如,我們有一個構(gòu)造函數(shù)Person,可以用來創(chuàng)建人的實例。我們可以使用instanceof檢查一個對象是否是Person的實例:

function Person(name) {
this.name = name;
}
var person = new Person("John");
console.log(person instanceof Person); // 輸出 true

在上面的例子中,person是通過Person構(gòu)造函數(shù)創(chuàng)建的實例,所以person instanceof Person返回true。

另外,instanceof運算符還可以用來檢查一個對象是否是其父類的實例,或者是其父類的父類的實例,以此類推。

function Animal() {}
function Cat() {}
Cat.prototype = Object.create(Animal.prototype);
var cat = new Cat();
console.log(cat instanceof Cat); // 輸出 true
console.log(cat instanceof Animal); // 輸出 true

在上面的例子中,cat是通過Cat構(gòu)造函數(shù)創(chuàng)建的實例,但是Cat的原型是通過Object.create方法繼承自Animal的原型。所以cat既是Cat的實例,也是Animal的實例。

0