如何简单理解js原型链

      //实例xu上没有say方法,会顺着原型链向上查找,构造函数上包含say方法,成功调用
      //__proto__是每个对象都有的属性,xu不是函数,没有prototype,构造函数Person包含prototype
      //__proto__可以理解为“构造器的原型”,即__proto__===constructor.prototype

      // 构造函数
      function Person(name, age) {
        this.name = name
        this.age = age
      }
      Person.prototype.say = function () {
        //this是什么要看执行的时候谁调用了这个函数。
        console.log("I'm " + this.name + " And I'm " + this.age)
      }
      const xu = new Person('徐同保', 30)
      xu.say() //I'm 徐同保 And I'm 30

      console.log(xu.say === xu.__proto__.say) //true
      console.log(xu.__proto__ === Person.prototype) //true
      console.log(xu.say === Person.prototype.say) //true

posted @ 2021-11-20 18:56  徐同保  阅读(0)  评论(0编辑  收藏  举报  来源