温故而知新,前面的知识多多少少遗忘了些,复习后写篇博客总结一下~
1. 初识
1.1内存图
通过下图,我们先有一个大概的认识~
- 使用对象模板(构造方法)Student创建对象的实例tom,这个就像妈妈生育了孩子
- 任何函数在创建的时候,会同时创建该函数的prototype属性,该属性引用的就是原型对象。原型对象就像爸爸,爸爸为孩子提供了公共属性和方法。如果创建了多个实例,各个实例内部有自己的自有属性,但这些实例都可以使用原型对象中的公共属性,就好比:亲兄弟俩各有自己的个性,也有继承自爸爸的共性
- 实例继承原型对象是通过_ _ proto_ _属性。这就像是孩子体内的基因,这个基因说明它就是其原型对象的孩子
1.2 代码
上图代码~
function Student(name,age){ //构造函数
this.name=name;
this.age=age;
}
Student.prototype.say=function(){ //设置公共属性
console.log("hello");
}
var tom = new Student("tom",19); //创建实例
var mary = new Student("mary",19);
tom.say();
mary.say();
console.log(tom);
console.log(mary);
2. 相知
2.1自有属性和原型属性
接上面栗子~
- 自有属性就好比tom有一块卡西欧手表,mary有一条粉色的裙子
tom.watch="CASIO";
mary.skirt="pink";
console.log(tom.watch); //CASIO
console.log(mary.skirt); //pink
- 原型属性就好比tom和mary是双胞胎,他们两生日一样
Student.prototype.birthday="2000/1/1";
console.log(tom.birthday) //2000/1/1
console.log(mary.birthday) //2000/1/1
- 自有属性会重写原型属性
function Hero(){
this.name="Spider man"
}
Hero.prototype.name="Iron Man";
var hero= new Hero();
console.log(hero.name); //Super man
delete hero.name;
console.log(hero.name); //Iron man
delete Hero.prototype.name;
console.log(hero.name); //undefined
2.2 原型链
我们还是看图来理解
图中红色的链路就是所谓的原型链~
- 原型对象本身也有原型
- 构造函数的原型对象中也有一个_ _ proto _ _属性,默认指向Object类型的原型对象——Object.prototype
- Object.prototype是所有对象的原型,它包含了所有对象的公共属性和方法,比如toString方法
- 所有对象通过_ _ proto _ _属性的引用关系,可以直接或间接引用到Object.prototype对象
- 使用对象的_ _ proto _ _属性形成的逐级引用的关系即为原型链
3. 三角恋
prototype、_ _ proto _ _和constructor的三角关系
通过上图可以总结得出:
- tom._ _ proto _ _=== Student.prototype
- tom自身不具有constructor属性,Student.prototype具有constructor属性并且指向了Student函数,所以tom通过_ _ proto _ _找到原型链中的constructor属性,即tom.constructor===Student
console.log(tom.__proto__===Student.prototype) //true
console.log(tom.constructor===Student) //true
console.log(Student.prototype.constructor===Student) //true
先总结到这儿了~
如果对你有帮助,点个赞支持一下吧~
本文借鉴了以下文章~
https://blog.csdn.net/cc18868876837/article/details/81211729
版权声明:本文为weixin_44410783原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。