2:手写 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;
        }
      }
      const person = new Person('Steven', 28);

      console.log(person.__proto__ === Person.prototype);
      console.log(person.__proto__.constructor === person.constructor);

      function myInstanceof(obj, className) {
        let pointer = obj;
        while (pointer) {
          if (pointer === className.prototype) {
            return true;
          }
          pointer = pointer.__proto__;
        }
        return false;
      }
      console.log(myInstanceof(person, Person));
    </script>
  </body>
</html>

 

posted @ 2022-04-25 10:33  苹果π  阅读(52)  评论(0编辑  收藏  举报