JavaScript-手写 instanceof 方法


手写instanceof方法

instanceof判断数据类型的原理

通过原型链来实现继承关系的判断(判断变量__proto__属性和构造函数prototype属性的指向是否相同)

  • 例1:判断num是否属于Number类型

    var num = new Number(1);
    console.log(num instanceof Number);	// true
    

    image-1

    可以看到num__proto__Numberprototype指向相同,所以instanceof返回为true

  • 例2:自定义函数继承,利用instanceof判断继承关系

    function Animal(name, calls) {
        this.name = name;
        this.say = function() {
            console.log(calls);
        }
    }
    
    const Cat = new Animal('猫', '喵');
    const Dog = new Animal('狗', '汪');
    

    image-2

    Cat.__proto__指向Animal,故Cat instanceof Animal返回true

    img-3

手写instanceof

function myInstanceof(left, right) {
    let proto = left.__proto__;
    let prototype = right.prototype;
    
    // proto为空,即遍历到原型链的尽头
    // prototype为空,传入的构造函数异常
    if (proto === null || prototype === null) {
        return false;
    } else if(proto === prototype){
        return true;
    } else {
        myInstanceof(proto, right);		// 递归,判断right是否left的原型链上
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM