JavaScript-Algorithms icon indicating copy to clipboard operation
JavaScript-Algorithms copied to clipboard

实现 instanceOf

Open sisterAn opened this issue 4 years ago • 2 comments

sisterAn avatar Mar 18 '21 00:03 sisterAn

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

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

xiaoerwen avatar Mar 19 '21 02:03 xiaoerwen

function myInstanceof(instance, target) {
    const targetProto = target.prototype,
              instanceProto = instance.__proto__;
    while(instanceProto) {
      if (instanceProto === targetProto) return true;
      instanceProto = instanceProto.__proto__;
   }
   return false;
}

evatxu avatar Apr 06 '21 01:04 evatxu