sisterAn / JavaScript-Algorithms

基础理论+JS框架应用+实践,从0到1构建整个前端算法体系
5.5k stars 633 forks source link

实现 instanceOf #161

Open sisterAn opened 3 years ago

xiaoerwen commented 3 years ago
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 commented 3 years ago
function myInstanceof(instance, target) {
    const targetProto = target.prototype,
              instanceProto = instance.__proto__;
    while(instanceProto) {
      if (instanceProto === targetProto) return true;
      instanceProto = instanceProto.__proto__;
   }
   return false;
}