# 实现instanceOf
# instanceof作用
检测构造函数的原型是否在实例的原型链上
# 原型链
# instanceOf实现
# 迭代
/**
* 检测构造函数的原型是否在实例的原型链上
* @param {object} a
* @param {Object} b
*/
function instanceOf(a, b) {
const prototype = b.prototype
let __proto__ = a.__proto__
while (1) {
if (__proto__ === prototype) {
return true
}
if (!__proto__) {
return false
}
__proto__ = __proto__.__proto__
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 递归
/**
* 检测构造函数的原型是否在实例的原型链上
* @param {object} a
* @param {Object} b
*/
function instanceOf(a, b) {
return a !== null && (a.__proto__ == b.prototype || instanceOf(a.__proto__, b))
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 测试代码
console.log(instanceOf([], Array));
console.log(instanceOf({}, Object));
console.log(instanceOf(/^$/, RegExp));
console.log(instanceOf(function () { }, Function));
console.log(instanceOf([], Function));
1
2
3
4
5
2
3
4
5