Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 instanceOf #161

Open
sisterAn opened this issue Mar 18, 2021 · 2 comments
Open

实现 instanceOf #161

sisterAn opened this issue Mar 18, 2021 · 2 comments
Labels

Comments

@sisterAn
Copy link
Owner

No description provided.

@xiaoerwen
Copy link

xiaoerwen commented Mar 19, 2021

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__;
    }
}

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

@evatxu
Copy link

evatxu commented Apr 6, 2021

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
Labels
Projects
None yet
Development

No branches or pull requests

3 participants