美文网首页
53.JS->手写instanceOf

53.JS->手写instanceOf

作者: wo不是黄蓉 | 来源:发表于2022-02-14 17:54 被阅读0次

如果一个实例的原型链中出现过相应的构造函数,则返回true

获取实例对象的原型对象:obj.__proto__
获取构造函数的原型对象:Person.prototype
他们都指向构造函数

1.使用递归实现

const myInstanceiof1 = (left, right) => {
  if (typeof left !== "object" || left === null) return false;
  let proto = left.__proto__;
  while (proto) {
    if (proto === right.prototype) {
      return true;
    }
    proto = myInstanceiof1(proto);
  }
  return false;
};

2.使用Object.getPrototypeOf实现

const myInstanceiof = (left, right) => {
  if (typeof left !== "object" || left === null) return false;
  let proto = Object.getPrototypeOf(left); //返回指定对象的原型
  while (true) {
    if (proto === null) {
      return false;
    }
    if (proto === right.prototype) return true;
    proto = Object.getPrototypeOf(proto);
  }
};

test

let obj = { name: "jane" };
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

console.log(obj instanceof Object, obj instanceof Person); //true false
console.log(
  myInstanceiof1(obj, Object),
  myInstanceiof1(obj, Person)
);

相关文章

网友评论

      本文标题:53.JS->手写instanceOf

      本文链接:https://www.haomeiwen.com/subject/oihhlrtx.html