value instanceof Constructor
不啰嗦,一句话阐述instanceof操作符的原理:
value的原型链中是否包含Constructor的原型对象
function myInstanceof(instance, constructor) {
const currentPrototype = Object.getPrototypeOf(instance)
if (currentPrototype === null) {
return false
}
if (currentPrototype.constructor === constructor) {
return true
}
return myInstanceof(currentPrototype, constructor)
}
console.log(myInstanceof([], Array)) // true
console.log(myInstanceof([], Object)) // true
console.log(myInstanceof([], Date)) // false
console.log(myInstanceof(() => { }, Function)) // true
console.log(myInstanceof(() => { }, Object)) // true
console.log(myInstanceof(() => { }, Array)) // false
console.log(myInstanceof({}, Object)) // true
console.log(myInstanceof({}, Function)) // false
console.log(myInstanceof({}, Array)) // false
欢迎评论,欢迎纠错,我们一起成长!
xyzh.work@foxmail.com
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。