美文网首页重学es6
class讲解之11 prototype 、__proto__、

class讲解之11 prototype 、__proto__、

作者: zhang463291046 | 来源:发表于2020-08-12 09:59 被阅读0次

    以下内容是引用或者借鉴别人的,自己只是做个笔记,方便学习。理解错误的地方,欢迎评论。如有侵权,私聊我删除,未经允许,不准作为商业用途

    实例与类之间的那点关系

    class A {
      constructor() {
        this.x = 1;
      }
      print() {
        
      }
    }
    let a = new A()
    console.log(a.__proto__ === A.prototype)  // true
    console.log(A === A.prototype.constructor)  // true
    

    图解


    image.png

    类与类之间的那点关系

    class B {
      constructor() {
        this.x = 2;
      }
      printB() {
    
      }
    }
    class A extends B {
      constructor() {
        super();
        this.x = 1;
      }
      print() {
    
      }
    }
    console.log(A.__proto__ === B);   // true
    console.log(A.prototype.__proto__ === B.prototype);   // true
    

    图解


    image.png

    实例与类、类与类的之间那点关系,最终形成原型链

    class B {
      constructor() {
        this.x = 2;
      }
      printB() {
    
      }
    }
    class A extends B {
      constructor() {
        super();
        this.x = 1;
      }
      print() {
    
      }
    }
    let a = new A();
    console.log(a.__proto__ === A.prototype)   // true
    console.log(a.__proto__.__proto__ === B.prototype)   // true
    console.log(a.__proto__.__proto__.__proto__ === Object.prototype)   // true
    

    图解


    image.png

    原型链作用:当调用实例对象的方法或读取实例对象的属性时,如果找不到,就会通过__proto__查找上一级实例原型中的方法或属性,如果还找不到,就去找原型的原型,一直找到最顶层为止。

    相关文章

      网友评论

        本文标题:class讲解之11 prototype 、__proto__、

        本文链接:https://www.haomeiwen.com/subject/fwgzrktx.html