JS手写代码篇---手写 instanceof 方法

2、手写 instanceof 方法

instancecof用于检测一个对象是否是某个构造函数的实例。它通常用于检查对象的类型,尤其是在处理继承关系时。

eg:

     const arr = [1,2,3,4,5]
     console.log(arr instanceof Array); // true
     console.log(arr instanceof Object); // true

那这是怎么实现的呢?

  • 每个对象都有一个原型,对象从其原型继承属性和方法。
  • 数组的直接原型是 Array.prototype
  • Array.prototype 的原型是 Object.prototype
  • Object.prototype 的原型是 null,表示原型链的终点。

这种原型链机制是 JavaScript 继承和原型继承的基础。通过原型链,JavaScript 实现了对象的属性和方法的继承。

我们就知道:

     console.log(arr.__proto__ === Array.prototype); // true
     console.log(arr.__proto__=== Object.prototype); // true
     console.log(arr.__proto__.__proto__ === Object.prototype); // true
     console.log(arr.__proto__.__proto__.__proto__ === null); // true

这就让我想到本道题木的解题思路:

在函数当中我们输入目标和待测类型,进行循环,如果原型链上有待测类型的原型返回true,没有也就是当了原型链的终点null,返回false

我的代码:

    function getIncetanceof(target , type){
        // 1、target的原型链
        let targetProto = target.__proto__;
        // 2、循环判断
        while(true){
            if(targetProto === null){
                return false;
            }else if(targetProto === type.prototype){
                return true;
            }else{
                // 都没有的时候就要更新targetProto
                targetProto = targetProto.__proto__;
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值