instanceof 操作符
语法: object instanceof constructor
instanceof 运算符用来检测 constructor.prototype 是否存在于参数 object 的原型链上。
js
function Animal(kind) {
this.kind = kind
}
let cat = new Animal('cat')
console.log(cat instanceof Animal) // true
console.log(cat instanceof Object) // true
console.log(cat instanceof Array) // false
/* 原理 */
console.log(cat.__proto__ === Animal.prototype) // true
console.log(cat.__proto__.__proto__ === Object.prototype) // true
思考:instanceof操作符会根据原型链逐步往上查找直到原型为null
模拟实现
js
function imitation(object, constructor) {
let proto = object.__proto__
let prototype = constructor.prototype
while (true) {
if (proto === null) return false
if (proto === prototype) return true
proto = proto.__proto__ /* 根据原型链向上查找 */
}
}
console.log(imitation(cat, Animal)) // true
console.log(imitation(cat, Object)) // true
console.log(imitation(cat, Array)) // false