2-6、手写instanceof

54 阅读1分钟

知识点

instanceof

  • instanceof 运算符用于检测构造函数 prototype 属性是否出现在某个实例对象的原型链上
  • 可以判断继承关系,只要是在同一条原型链上,就可以返回true
<script>
    class Person {
        constructor(name) {
            this.name = name;
        }
    }
    class Student extends Person {
        constructor(name, age) {
            super(name);

            this.age = age;
        }
    }
    const zhangsan = new Student('张三', 18);
    console.log(myInstanceof(zhangsan, Student));
    console.log(myInstanceof(zhangsan, Person));
    console.log(myInstanceof(zhangsan, Object));
    console.log(myInstanceof(zhangsan, Array));
    function myInstanceof(obj1, obj2) {
        // 声明一个变量
        let obj1Proto = obj1.__proto__;
        // 循环执行判断proto的上一级
        while (true) {
            if (obj1Proto === null) {
                return false;
            } else if (obj1Proto === obj2.prototype) {
                return true;
            }
            obj1Proto = obj1Proto.__proto__;
        }   
    }
</script>