一、概述
JavaScript 的 instanceof 運算符用於檢測構造函數的 prototype 屬性是否出現在某個實例對象的原型鏈上。
function Foo() {} function Bar() {} let foo = new Foo() console.log(foo instanceof Foo) // true console.log(foo instanceof Bar) // false
在上面的例子中,由於 foo 的原型鏈中出現了 Foo.prototype,因此 foo instanceof Foo 的結果是 true。
需要注意的是,instanceof 判斷的是實例的原型鏈上是否出現過該構造函數的 prototype 屬性,而不是判斷實例本身是否為該構造函數。
二、使用
instanceof 運算符通常用於判斷某個對象是否為某種類型。
function People(name, age) { this.name = name this.age = age } function Student(name, age, grade) { this.name = name this.age = age this.grade = grade } let john = new People('John', 20) let mary = new Student('Mary', 18, '高中三年級') console.log(john instanceof People) // true console.log(mary instanceof Student) // true console.log(mary instanceof People) // true
在上面的例子中,即使 Student 沒有明確繼承 People,但是由於 Student 的原型鏈中包含了 People.prototype,所以可以判斷 mary instanceof People 為 true。
三、注意事項
在使用 instanceof 運算符時,需要注意以下幾點:
1. instanceof 右側必須是一個函數。
2. instanceof 運算符不能正確判斷基本類型,因為基本類型不是對象。
console.log('hello' instanceof String) // false console.log(123 instanceof Number) // false
3. instanceof 可能被修改,導致結果不是預期的。
function Foo() {} function Bar() {} Bar.prototype = new Foo() let b = new Bar() console.log(b instanceof Bar) // true console.log(b instanceof Foo) // true // 修改 Bar.prototype Bar.prototype = {} console.log(b instanceof Bar) // false console.log(b instanceof Foo) // true,由於對象 b 的原型鏈沒有發生改變
四、總結
JavaScript 的 instanceof 運算符是一種用於判斷對象是否屬於某個類型的工具。它的判斷方式是檢測對象的原型鏈中是否出現了某個構造函數的 prototype 屬性。在使用過程中需要注意避免修改構造函數的 prototype,以及判斷基本類型時的局限性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/291821.html