当前位置:网站首页>js中的原型和原型链
js中的原型和原型链
2022-07-01 02:36:00 【爱前端的茂茂】
JS的原型和原型链算是前端面试题的热门题目了,基本上遇见的概率会很大吧!
首先,什么是原型?
每一个javascript对象(除null外)创建的时候,就会与之关联另一个对象,这个对象就是我们所说的原型,每一个对象都会从原型中“继承”属性。
举个例子:
function Person(age) {
this.age = age
}
Person.prototype.name = 'kavin'
var person1 = new Person()
console.log(person1.name) //kavin就是说在通过构造函数创建实例的时候,如果去实例中找寻某个属性值的时候,如果他有的话就会直接输出,如果没有的话,就会去它的原型对象中去找。

prototype:每个函数都有一个prototype属性,这个属性指向函数的原型对象。
__proto__:这是每个对象(除null外)都会有的属性,叫做__proto__,这个属性会指向该对象的原型。
constructor:每个原型都有一个constructor属性,指向该关联的构造函数。
原型相关的知识考点一般就是围绕这张图,那怎么去验证这张图的正确性呢?
console.log(Person===Person.prototype.constructor) // true
console.log(person.__proto__ == Person.prototype) // true
console.log(person.__proto__.constructor == Person) // true
console.log(person.constructor == Person) // true然后什么是原型链呢?
单的回顾一下构造函数、原型和实例的关系:每个构造函数都有一个原型对象,原型对象都包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。那么假如我们让原型对象等于另一个类型的实例,结果会怎样?显然,此时的原型对象将包含一个指向另一个原型的指针,相应地,另一个原型中也包含着一个指向另一个构造函数的指针。假如另一个原型又是另一个类型的实例,那么上述关系依然成立。如此层层递进,就构成了实例与原型的链条。
简单的表达就是:上边说道如果实例没有一个属性,它会去它的原型中去找,但是如果它的原型中也没有这个属性呢,会停止寻找么,不一定,因为它的原型可能也有自己的原型,这个时候他就会去它的原型的原型中去寻找,这个时候会停下么,还是不一定,要看他原型的原型有没有原型,这样就形成了一条原型链。
直到最后一个找不到原型时返回null

边栏推荐
猜你喜欢

DenseNet网络论文学习笔记
![[2022] Jiangxi postgraduate mathematical modeling scheme and code](/img/f4/86b0dc2bd49c3a54c1e0538b31d458.png)
[2022] Jiangxi postgraduate mathematical modeling scheme and code
![Pytorch —— 基礎指北_貳 高中生都能看懂的[反向傳播和梯度下降]](/img/6e/279dbb7a8d7a5ecd240de464c5b8b2.png)
Pytorch —— 基礎指北_貳 高中生都能看懂的[反向傳播和梯度下降]

SWT / anr problem - storagemanagerservice stuck

Nacos configuration center tutorial

CentOS installs multiple versions of PHP and switches

Pycharm 打开远程目录 Remote Host

halcon变量窗口的图像变量不显示,重启软件和电脑都没用

Youmeng (a good helper for real-time monitoring of software exceptions: crash) access tutorial (the easiest tutorial for Xiaobai with some foundation)

Go import self built package
随机推荐
MnasNet学习笔记
Applet custom top navigation bar, uni app wechat applet custom top navigation bar
Pulsar Geo Replication/灾备/地域复制
ipmitool下载地址和编译安装时可能出现的问题
The latest wechat iPad protocol code obtains official account authorization, etc
Ipmitool download address and possible problems during compilation and installation
Rocketqa: cross batch negatives, de noised hard negative sampling and data augmentation
go: finding module for package
Objects and object variables
产业互联网中,「小」程序有「大」作为
Alphabet rearrange inator 3000 (dictionary tree custom sorting)
【PR #5 A】双向奔赴(状压DP)
Pulsar的Proxy支持和SNI路由
7_ Openresty installation
Some uses of Halcon array
What is PMP?
Leetcode(524)——通过删除字母匹配到字典里最长单词
Small program cloud development -- wechat official account article collection
鼠标悬停效果二
(summary I) Halcon Foundation's target finding features + becoming a regular