当前位置:网站首页>Teach you to learn JS prototype and prototype chain hand in hand, a tutorial that monkeys can understand
Teach you to learn JS prototype and prototype chain hand in hand, a tutorial that monkeys can understand
2022-07-06 19:35:00 【Front end technology station】
Today I want to share with you an article about JS It's very difficult to understand , And I often ask about the prototype and prototype chain during the interview .

Do you look familiar with the above picture ? Maybe I feel confused when I see it for the first time , I thought to myself what this is ? What should I think of so many lines ? In fact, when I first saw it, I was also very confused , puzzled , After slowly understanding some simple principles , Looking back , In fact, it's not so difficult . Now, ladies and gentlemen of the audience, follow me, a rookie, and use it as simple as possible , Simple language , Take your time to analyze , Take your time to understand , Believe that you can also learn !
1 The relationship between constructor and prototype object
Collected front-end interview question bank
1.1 Know the prototype object :
When we use function Keyword to create a function , In fact, a memory containing prototype Object of property , This attribute object points to the prototype object of the constructor .
function Foo() {
}
console.log(Foo.prototype);//constructor: ƒ Foo()
therefore : The relationship between constructor and prototype object is illustrated below :
2 The relationship between function instances and prototype objects
2.1: Recognize function instances
__proto__ Is every division null External JavaScript Objects have a property , It points to the Prototype object
function Foo() {
}
var fo = new Foo();
since prototype and __proto__ Point to the prototype object of the object constructor , that prototype and __proto__ What is the relationship ? Is it equal ? Now let's start the demonstration
console.log(fo.__proto__ === Foo.prototype); //true
You can see the print fo.__proto__=== Foo.prototype return true Maybe for students who love learning, they may ask again , Why are they equal ? Can you demonstrate the process , well Don't worry , Look, I'll slowly decompose it for you . We can see fo The object is new Coming out , Well, students, think about it new What did you do ? Actually new I did the following things :
2.2: Functional new The main steps are as follows :
- An empty object is created in memory ;
- Inside this object [[prototype]] Property will be assigned to the class prototype attribute ;
- In the constructor this, Will point to the new object created ;
- Execute code in constructor
- If the constructor does not return a non empty object , Then return the created new object
Let's use pseudo code to demonstrate
function Foo() {
}
var fo = new Foo();
console.log(fo.__proto__ === Foo.prototype); //true
The following is the simulation data
function Foo() {
var moni={}
moni.__proto__=Foo.prototype// This step is very important
this=moni
...
return moni
}
var fo=Foo()
You can see the pseudo code above moni.__proto__=Foo.prototype In fact, this can be found moni.__proto__ It's pointing to Foo.prototype, So we can know moni.__proto__ The memory address pointed to is and Foo.prototype It points to the same memory address .
Both : fo.__proto__ === Foo.prototype yes true
since Foo.prototype Points to a prototype object
that fo.__proto__ It's also a direction Foo.prototype The prototype object pointed to
You can see the following code list :
function Foo() {
}
var fo = new Foo();
var f1 = new Foo();
console.log(fo.__proto__ === Foo.prototype); //true
console.log(f1.__proto__ === Foo.prototype); //true
console.log(fo.__proto__ === f1.__proto__); //tru
therefore : The relationship between the function instance and the prototype object is illustrated as follows :

3 Prototype object (constructor And proto) Direct relationship with constructor
When we use Foo.prototype When printing, you will find the following information , One is constructor, The other is __prto__( In fact, it represents this [[Prototype]]), Let's discuss this first constructor, We will discuss this later __proto__
3.1: In the prototype object constructor Relationship with constructor
Say first conclusion : In the prototype object constructor Is pointing to the constructor Of . You might say Words alone are no proof , I want you to prove it to me . Since you have such doubts , Then I will satisfy you .
function Foo() {
}
var fo = new Foo();
console.log(Foo.prototype.constructor);//ƒ Foo() {}
Print the results

We will find that Foo.prototype.constructor It's pointing Foo Of this constructor . Next, let's do a step of verification , Let's see if it's true .
function Foo() {
}
var fo = new Foo();
console.log(Foo.prototype.constructor===Foo);//true
We will find that Foo.prototype.constructor===Foo yes true, So we can be sure that Foo.prototype.constructor It means pointing. Foo Functional
So in the prototype object constructor The relationship with constructor is illustrated as follows :
3.2: In the prototype object __proto__ Relationship with constructor
You may think of the prototype object __proto__ Is it pointing to Foo Well ? It's not . Look at the code below
console.log(Foo.prototype.__proto__===Foo)//false
We will find that printing is false, So whose is it pointing to ? That's a good question , Who on earth does he point to , Just print it and have a look We will be surprised to find Foo.prototype.__proto__ Pointing to Object The prototype of the . You may have doubts again , Why is Object? Actually Object It's the prototype at the top , Without this limitation , When looking for a nonexistent data according to the prototype chain , How can we know it's not found !!
So we can conclude that Foo.prototype.__proto__ Pointing to Object.prototype
demonstration :Foo.prototype.__proto__ Is it pointing to Object.prototype
function Foo() {
}
var fo = new Foo();
console.log(Foo.prototype.__proto__===Object.prototype)//true
It can be seen that their printing is equal , So as I said before Foo.prototype.__proto__===Object.prototype The conclusion is true . Careful students may have such questions ?Object.prototype__proto__ To whom ? In fact, it points to null.
console.log(Object.prototype.__proto__)//null
In fact, we can still throw a question here ? Now that we know Object Function prototype object , It must have its own constructor, Then it's constructor Who is it ? Let's continue to discuss .
3.3:Object Function prototype and constructor Relationship
Conclusion :Object In the prototype constructor Pointing to Object function .
Code validation is as follows :
console.log(Object.prototype.constructor)
After printing, we found that it points to Object Function of , Continue to verify
console.log(Object.prototype.constructor===Object)
So here we can definitely see Object.prototype.constructor It means pointing. Object Functional . since Object Is a function, it must also have its own Prototype Of , its Prototype It must point to Object Function prototype object of .
therefore :Object Function prototype and constructor Relationship

In fact, it has been formed here Prototype chain 了 , We can find if fo I can't find it on my prototype , He will find the prototype of the parent class , Look up layer by layer , In fact, it's like a chain , So it's called Prototype chain . Of course, here is not endless , If you can't find it, you'll return null.
In fact, we have almost mastered the most basic prototype knowledge here . But in fact, we can continue to discuss ,Foo Functions and Object Function does it have __proto__ Well ? It's actually Yes Of , Why? ? because The essence of a function is also an object , Next, we will discuss whether a function is an object .
4 Function is also an object
function bar() {}
bar.names = " Goya ";
console.log(bar.names);
By printing, we do see names Printed , So we can also prove Function is indeed an object , It's just a Special objects nothing more . So we can say the above Foo Functions and Object Function is also an object . Since it is an object, it must also have its own __proto__, So it's __proto__ To whom ?
5 Functional __proto__
Conclusion : Functional __proto__ In fact, it points to Functon Prototype object .
Let's verify it , The specific code is as follows
function Foo(){}
var p1 = new Foo();
console.log(Person.__proto__)

This may not be obvious , Let's use another method to verify , as follows :
function Foo() {}
var p1 = new Foo();
console.log(Foo.__proto__)
console.log(Foo.__proto__===Function.prototype)
console.log(Object.__proto__===Function.prototype)
console.log(Foo.__proto__===Object.__proto__)

So we can say function __proto__ In fact, it points to Functon Prototype object . namely Object/Foo All are Fuction Instance object of
therefore : Functional __proto__ Point to Function The diagram of the prototype of is as follows :

6Function Prototype and prototype chain of
6.1:Function Direction in prototype
6.1.1:Function In the prototype constructor
Conclusion :Function In the prototype constructor The direction of Function function
We can use Foo This function is used to verify , The code is as follows :
function Foo() {}
//Foo.__proto__: This is already Function The prototype object
console.log(Foo.__proto__.constructor === Function);

By printing, we can see Function In prototype object constructor In fact, it points to Function function . So it's __proto__ Who is it pointing to ?
6.1.2:Function In the prototype __proto__ The direction of
Conclusion :Function In the prototype __proto__ Pointing to Object Prototype object
function Foo() {}
//Foo.__proto__: This is already Function The prototype object
console.log(Foo.__proto__.__proto__===Object.prototype);

By printing, we can see Function In prototype object __proto__ In fact, it points to Object Of the prototype object . It's easy to understand , The prototype object is an object , Since it is an object, it must have its own prototype , We all know that the parent class of all objects is Object.
therefore :Function Diagram of prototype object :

6.2:Function Prototypes of functions
6.2.1:Function In the prototype of function prototype
We can know from the previous summary , Function prototype Is pointing to the prototype object of the function . So here we are Function Function prototype It means pointing. Functon The prototype object of the function .
6.2.2:Function In the prototype of function __proto__
Conclusion :Function In the prototype of function __proto__ It's pointing Funtion Prototype . The code is as follows :
console.log(Function.__proto__===Function.prototype)

You can see that the printing is true, explain Function Of __proto__ It means pointing. Function Prototype Of . In fact, we combine 6.1 You can know all the functions __proto__ All point to functions Prototype object Of . And here it It is Function So point to yourself Prototype object .
Now look at the following picture, it will become very simple , It can be roughly divided into 3 Large module , I use serial number to divide .

The above figure can be disassembled into such a function , In combination with my above analysis It's actually very easy
function Foo(){
}
let f1=new Foo()
let f2=new Foo()Collected front-end interview question bank

边栏推荐
- LeetCode_格雷编码_中等_89.格雷编码
- First day of rhcsa study
- 黑马--Redis篇
- Fast power template for inverse element, the role of inverse element and example [the 20th summer competition of Shanghai University Programming League] permutation counting
- 系统性详解Redis操作Hash类型数据(带源码分析及测试结果)
- 时钟轮在 RPC 中的应用
- usb host 驱动 - UVC 掉包
- How to customize animation avatars? These six free online cartoon avatar generators are exciting at a glance!
- Intelligent supply chain management system solution for hardware and electromechanical industry: digital intelligent supply chain "creates new blood" for traditional industries
- GCC【7】- 编译检查的是函数的声明,链接检查的是函数的定义bug
猜你喜欢

LeetCode_双指针_中等_61. 旋转链表

Cereals Mall - Distributed Advanced p129~p339 (end)

Live broadcast today | the 2022 Hongji ecological partnership conference of "Renji collaboration has come" is ready to go

LeetCode-1279. 红绿灯路口

Using clip path to draw irregular graphics

【计算情与思】扫地僧、打字员、信息恐慌与奥本海默
![[translation] micro survey of cloud native observation ability. Prometheus leads the trend, but there are still obstacles to understanding the health of the system](/img/63/3addcecb69dcb769c4736653952f66.png)
[translation] micro survey of cloud native observation ability. Prometheus leads the trend, but there are still obstacles to understanding the health of the system

第五期个人能力认证考核通过名单公布

Solution of commercial supply chain management platform for packaging industry: layout smart supply system and digitally integrate the supply chain of packaging industry

ACTF 2022圆满落幕,0ops战队二连冠!!
随机推荐
黑马--Redis篇
Dark horse -- redis
【翻译】云原生观察能力微调查。普罗米修斯引领潮流,但要了解系统的健康状况仍有障碍...
Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)
MRO industrial products enterprise procurement system: how to refine procurement collaborative management? Industrial products enterprises that want to upgrade must see!
关于图像的读取及处理等
思維導圖+源代碼+筆記+項目,字節跳動+京東+360+網易面試題整理
Fast power template for inverse element, the role of inverse element and example [the 20th summer competition of Shanghai University Programming League] permutation counting
Using clip path to draw irregular graphics
Mathematical knowledge -- code implementation of Gaussian elimination (elementary line transformation to solve equations)
安装Mysql报错:Could not create or access the registry key needed for the...
C # - realize serialization with Marshall class
Swiftui game source code Encyclopedia of Snake game based on geometryreader and preference
反射及在运用过程中出现的IllegalAccessException异常
MySQL information schema learning (I) -- general table
Computer network: sorting out common network interview questions (I)
121. 买卖股票的最佳时机
思维导图+源代码+笔记+项目,字节跳动+京东+360+网易面试题整理
通俗的讲解,带你入门协程
MATLAB中deg2rad和rad2deg函数的使用