JS instanceof 的本质

JS 之父原本是 Scheme 程序员,在接到设计一门

1
2
3
4
5
6
function Person (name) {
this.name = name
}

const p = new Person("lgy")
console.log(p instanceof Person) // true

p instanceof Person 时到底发生了什么呢?《You Don’t Know JS》书中给出了答案:

其实是在p的原型链上,依次查找Person.prototype, 如果找到,即返回true,否则返回false

我们实现一个 instanceof_ 函数, 实现类似的效果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function instanceof_ (instance, ctor) {
const prototypeOfCtor = ctor.prototype

let prototype = instance.__proto__
while (prototype) {
if (prototype === prototypeOfCtor) {
return true
}

prototype = prototype.__proto__
}
return false
}

console.log(instanceof_(p, Person)) // true