手写:javascript中的关键字instanceof

instanceof是干嘛的?

首先,引用mdn的描述

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

在javascript中,查看基本数据类型的类型可以用关键字typeof,但是如果是要验证一个引用数据类型的话,就需要用到关键字instanceof,instance就是实例的意思,那么这个关键字就是用于判断,某某对象是不是某某类的实例,比如

function Person(name, age){
    this.name = name;
    this.age = age;
}

let person1 = new Person("张三", 25);
let person2 = {
    name : "张三",
    age : 25
}

console.log(person1 instanceof Person); // true
console.log(person2 instanceof Person); // false

这就说明person1是由Person实例化出来的对象,而person2不是,那么如果让person2的原型指向Person的原型对象呢?结果还是这样嘛?

person2.__proto__ = Person.prototype;
console.log(person2 instanceof Person); // ture

结果当然是为true,但是如果存在继承关系呢,比如现在有一个Children类,继承与Person,那么我children的实例用instanceof Person结果是否为真呢?

function Person(){}
function Children(){}

// 继承 Person的实例作为作为Children的原型
Children.prototype = new Person;

let children = new Children();

console.log(children instanceof Person);// true

结果为真,正好也应了mdn的介绍那样,instanceof了解到这里,我们就可以开始写instanceof的实现了

手写

定义一个函数叫myInstanceof,接收两个参数,第一个为instance,第二个为要Constructor,返回值为boolean,函数内的实现其实就是对instance的原型链进行遍历(其实就是一个链表遍历),如果遍历到了某一项原型 等于这个Constructor的原型,则返回true

function myInstanceof(instance, Constructor){
    if(typeof instance !== "object"){
        throw "the instance must be 'Object'";
    }
    if(typeof Constructor !== "function"){
        throw "the Contructor must be 'Function'"
    }   

    let prototype = instance.__proto__;
    // 遍历链表用while
    while(prototype){
        if(!prototype.__proto__){
            return false;
        }else if(prototype === Constructor.prototype){
            return true;
        }else{
            prototype = prototype.__proto__;
        }
    }
}

最后我们用前面的例子来验证一下

console.log(myInstanceof(children, Person));// true
posted @ 2020-09-25 10:15  j植树  阅读(395)  评论(0编辑  收藏  举报