instanceof 運算符用于檢測構(gòu)造函數(shù)的 prototype 屬性是否出現(xiàn)在某個實例對象的原型鏈上。
大白話就是判斷某個實例是否屬于某個類型或者屬于它的父類、祖先類...
function Parent () {
this.nums = 100
}
function Child (chi) {
this.chi = chi
}
Child.prototype = new Parent() // 原型鏈繼承
const ming = new Child('tennis')
ming instanceof Child // true
ming instanceof Parent // true
Child通過原型鏈繼承的方式繼承了Parent,所以ming不僅屬于Child類型也屬于Parent類型。知道了instanceof的用法,那下面就來實現(xiàn)一下。
我們要判斷A是不是屬于B這個類型,只需要當A的原型鏈上存在B即可,即A順著__proto__向上查找,一旦能訪問到B的原型對象B.prototype,表明A屬于B類型,否則的話A順著__proto__最終會指向null。
while循環(huán),此時此刻,非你莫屬。
function new_instanceof(left, right) {
let _left = left.__proto__
while (_left !== null) {
if (_left === right.prototype) {
return true
}
_left = _left.__proto__
}
return false
}
這就是instanceof的主要原理,嗯,只有這幾行,超級簡單,還能串聯(lián)一波原型、原型鏈,它不香嗎...