原型链和instanceof

151 阅读1分钟

看了下之前的笔记,这边关于原型链再做个总结,顺便在手写下instanceof.基础知识还是很重要的。

  1. 所有的引用类型,都具有对象特性,既可以自由扩展属性(除了“null”以外).
  2. 所有的引用类型,都有一个__proto__属性,属性值是一个普通对象.
  3. 所有的函数,都有一个prototype属性,属性值也是一个普通的对象.
  4. 所有的引用类型,__proto__属性值指向它的构造函数“prototype”属性值.
  5. 当试图得到一个对象的某个属性时,如果这个对象本身没有这个属性,那么会去他的__proto__(即它的构造函数prototype)中寻找.

原型链.png

function testInstancof(intance,origin){
    if(instance == null) return false;
    const type = typeof instance;
    if(type !=='object' && type !== 'function') return false;
    let tempInstance = instance;
    While(tempInstance){
        if(tempInstance.__proto === origin.prototype) return true;
        tempInstance = tempInstance.__proto__
    }
    return false
}