Skip to content

实现 instanceOf #161

Open
Open

Description

@sisterAn
No description provided.

Activity

  1. xiaoerwen commented on Mar 19, 2021

    @xiaoerwen
    Object.prototype.fakeInstanceOf = function(constructor) {
        let obj = this;
        while (true) {
            if (obj.__proto__ === null) {
                return false;
            }
            if (obj.__proto__ === constructor.prototype) {
                return true;
            }
            obj = obj.__proto__;
        }
    }

    考察的是原型链的使用,判断一个对象是否是某个构造函数的实例,即看构造函数的原型是否在该对象的原型链上。

  2. evatxu commented on Apr 6, 2021

    @evatxu
    function myInstanceof(instance, target) {
        const targetProto = target.prototype,
                  instanceProto = instance.__proto__;
        while(instanceProto) {
          if (instanceProto === targetProto) return true;
          instanceProto = instanceProto.__proto__;
       }
       return false;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions