文章目录加载中
JavaScript基础-instanceof
instanceof
是通过原型链来进行判断的,所以只要不断地通过访问__proto__
,就可以拿到构造函数的原型prototype
。直到null
停止。
/**
* 判断left是不是right类型的对象
* @param {*} left
* @param {*} right
* @return {Boolean}
*/
function instanceof2(left, right) {
let prototype = right.prototype;
// 沿着left的原型链, 看看是否有何prototype相等的节点
left = left.__proto__;
while (1) {
if (left === null || left === undefined) {
return false;
}
if (left === prototype) {
return true;
}
left = left.__proto__;
}
}
/**
* 测试代码
*/
console.log(instanceof2([], Array)); // output: true
function Test() {}
let test = new Test();
console.log(instanceof2(test, Test)); // output: true
本文来自心谭博客:xin-tan.com,经常更新web和算法的文章笔记,前往github查看目录归纳:github.com/dongyuanxin/blog
0