定義和用法
instanceof 運算符用來檢測 constructor.prototype 是否存在於參數 object 的原型鏈上。
語法: object instanceof constructor
object
要檢測的對象.constructor
某個構造函數
實現 instanceof
function instanceof(left, right) {
// 獲得類型的原型
let prototype = right.prototype
// 獲得對象的原型
left = left.__proto__
// 判斷對象的類型是否等於類型的原型
while (true) {
if (left === null)
return false
if (prototype === left)
return true
left = left.__proto__
}
}
參考資料:
前端進階之道