手写 instanceof 第二遍

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>手写 instanceof 第二遍</title>
  </head>
  <body>
    <script>
      class Person {
        constructor(name, age) {
          this.name = name;
          this.age = age;
        }
      }
      let person1 = new Person('', 29);
      let person2 = Reflect.construct(Person, ['', '18']);
      console.log(person1 instanceof Person);
      console.log(person2 instanceof Person);
      function myInstanceOf(obj, className) {
        let pointer = obj;
        while (pointer) {
          if (pointer === className.prototype) {
            return true;
          }
          pointer = Reflect.getPrototypeOf(pointer);
        }
        return false;
      }
      console.log(myInstanceOf(person1, Person));
    </script>
  </body>
</html>

 

posted @ 2022-05-06 21:35  苹果π  阅读(6)  评论(0编辑  收藏  举报