【博学谷学习记录】超强总结,用心分享|原型对象-原型链

54 阅读1分钟

原型对象

1.prototype(原型):每一个构造函数都有一个名为 prototype 的属性

<script>
  function Person() {
    
  }

  // 每个函数都有 prototype 属性
  console.log(Person.prototype);
</script>

2.constructor(构造器):每个原型对象都具有 constructor 属性代表了该原型对象对应的构造函数。

   <script>
      function Person() {
    
      }

    // 每个prototype都具有constructor 属性
   console.log(Person.prototype.constructor);
   console.log(Person.prototype.constructor === Person); //结果为true   

   </script>

image.png 3._proto_:(隐式原型):对象中包括了一个非标准备的属性 __proto__ 它指向了构造函数的原型对象 他们三者的关系

     <script>
      function Person() {
    
      }

    // 对象中包括了一个非标准备的属性 __proto__ 它指向了构造函数的原型对象
    const per = new Person()
    console.log(per.__proto__)
    console.log(per.__proto__.constructor === Person) //结果为true

   </script>

image.png

继承

基于构造函数原型对象实现面向对象的继承特性。

<script>
          
          function Person(){
            this.eat =function(){
                console.log('吃饭')
            }

          }

         function Woman(){
            this.gender = '女'
          }

          function Man(){
            this.gender = '男'
          }
            
           //让Woman的原型对象指向Person()
           // 子类的原型 =  new 父类  
          Woman.prototype = new Person()
          // 指回原来的构造函数
          Woman.prototype.constructor = Woman
           
          Man.prototype = new Person()
          Man.prototype.constructor = Man

          const w = new Woman()
          w.eat()   

          const m = new Man()
          m.eat()   

        
    </script>

原型链

基于原型对象的继承使得不同构造函数的原型对象关联在一起,并且这种关联的关系是一种链状的结构,我们将原型对象的链状结构关系称为原型链

image.png

<script>
  // Person 构造函数
  function Person() {
    this.arms = 2;
    this.walk = function () {}
  }
	
  // Person 原型对象
  Person.prototype.legs = 2;
  Person.prototype.eyes = 2;
  Person.prototype.sing = function () {}
  Person.prototype.sleep = function () {}
	
  // Chinese 构造函数
  function Chinese() {
    this.skin = 'yellow';
    this.language = '中文';
  }
	
  // Chinese 原型对象
  Chinese.prototype = new Person();
  Chinese.prototype.constructor = Chinese;
	
  // 实例化
  let c1 = new Chinese();

  console.log(c1);
</script>