首页 > 其他 > 详细

手写 instanceof 方法

时间:2021-05-31 00:15:03      阅读:29      评论:0      收藏:0      [点我收藏+]

手写instanceof方法

instanceof判断数据类型的原理

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

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

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

    技术分享图片

    可以看到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(‘狗‘, ‘汪‘);
    

    技术分享图片

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

    技术分享图片

手写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的原型链上
    }
}

手写 instanceof 方法

原文:https://www.cnblogs.com/chenjy259/p/14829268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!