浅谈对js原型对象的理解

1. __proto__prototype

__proto__服务于函数对象
prototype服务于函数实例化的对象
函数也是对象的一种

function App(){}
const a = new App()
a.__proto__ === App.prototype

构造函数与构造函数实例对象的原型链如图所示:
在这里插入图片描述

2. 对象原型 proto

  • __proto__对象原型与原型对象prototype是等价的
  • 对象都会有一个属性__proto__指向构造函数的prototype原型对象,之所以我们对象可以使用构造函数prototype原型对象的属性和方法,就是因为对象有__proto__原型的存在
 function Student(name, age) {
      this.name = name;
      this.age = age
    }
    Student.prototype.say = 'hello'
    Student.prototype.sing = function () {
      console.log('singing');
    }
    var student1 = new Student('ls', 18)
    // console.dir()可以显示一个对象的所有属性和方法
    console.dir(Student);
    console.log(student1); //对象身上系统会自动添加一个__proto__,指向构造函数的原型对象prototype
    //方法查找规则:首先先看student1身上是否有sing方法,如果有就执行这个对象上的sing
    // 如果student1身上没有这个方法,因为有__proto__的存在,就去构造函数原型对象prototype身上去查找所需要的方法

3. constructor 构造函数

  • 对象原型(_ _ proto _ _)和构造函数(prototype)原型对象里面都有一个属性constructor属性,constructor称之为构造函数,因为它指回构造函数本身

  • constructor主要用于记录该对象引用于那个构造函数,它可以让原型对象重新指向原来的构造函数

    如果我们修改了原来的构造函数,给原型对象赋值的是一个对象,则必须手动利用constructor指回原来的构造函数

4. 继承

    function Father() { }
    function Son() { }
    Father.prototype.skill = 'play'
    Son.prototype = new Father() //Son的原型对象指向Father的实例对象,Father的实例对象可以通过__proto__来访问Father原型对象。Father的实例对象与Father原型对象不是同一个对象
	Son.prototype.constroctor = Son
    var son = new Son();
    var father = new Father()
    console.log(son.skill) //play
    Son.prototype.say = 'hello'
    console.log(father.say); //undefined
    console.log(son.say);//hello

猜你喜欢

转载自blog.csdn.net/weixin_43950643/article/details/106601708