


Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain
Why can't I use objects on the prototype chain? And what is the underlying principle of the JS prototype chain?
When you first come into contact with the JS prototype chain, you will come into contact with a familiar term: prototype
; if you have ever gone deep into prototype
, you will come into contact with it Another noun: __proto__
(note: there are two underlines on both sides, not one). The following will be explained around the two terms prototype
and __proto__
1. Why objects cannot be used on the prototype chain:
Let’s take a very simple example first. I have a class called Humans (human beings), and then I have an object called Tom (a person) and another object called Merry (another person). Obviously Tom and Merry are obtained after instantiating the Humans class. Then this example can be written as the following code:
function Humans() { this.foot = 2; } Humans.prototype.ability = true;var Tom = new Humans();var Merry = new Humans(); console.log(Tom.foot);//结果:2console.log(Tom.ability);//结果:trueconsole.log(Merry.foot);//结果:2console.log(Merry.ability);//结果:true
The above is a very simple object-oriented example. I believe everyone can understand it. If you try Modify Tom's ability attribute, then
function Humans() { this.foot = 2; } Humans.prototype.ability = true;var Tom = new Humans();var Merry = new Humans(); Tom.ability = false; console.log(Tom.foot);//结果:2console.log(Tom.ability);//结果:falseconsole.log(Merry.foot);//结果:2console.log(Merry.ability);//结果:true
It can be seen from the above that the value of Tom's ability attribute has changed, but it does not affect the value of Merry's ability attribute. This is exactly the result we want, and it is also object-oriented. The advantage is that objects instantiated from the same class do not interfere with each other; OK, what about replacing ability with object objects? The code is as follows:
function Humans() { this.foot = 2; } Humans.prototype.ability = { run : '100米/10秒', jump : '3米'};var Tom = new Humans();var Merry = new Humans(); Tom.ability = { run : '50米/10秒', jump : '2米'};console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'100米/10秒'console.log(Merry.ability.jump); //结果:'3米'
The above code is in the prototype chain Object is used on the above code, but it can be seen from the above code that the change of Tom's ability attribute will not affect Merry's ability attribute at all, so you may think that there is nothing wrong with this approach. Why can't you use objects on the prototype chain? ?The following code will look very different, and can fully express the danger of using objects on the prototype chain:
function Humans() { this.foot = 2; } Humans.prototype.ability = { run : '100米/10秒', jump : '3米'};var Tom = new Humans();var Merry = new Humans(); Tom.ability.run = '50米/10秒'; Tom.ability.jump = '2米';console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'50米/10秒'console.log(Merry.ability.jump); //结果:'2米'
Yes, from the output of the above code, we can see that Tom’s ability attribute The change affects Merry's ability attribute, so we can understand that using objects on the prototype chain is very dangerous. It can easily break the mutual independence between instantiated objects. This is why objects cannot be used on the prototype chain. ?Yes, but what I want to say is not just that, but the principle. After reading the deep principles of the JS prototype chain later, I believe you will fully understand it.
Before explaining the deep principles of the JS prototype chain in the second part below, let’s first clarify a concept: The properties or methods on the prototype chain are all shared by instantiated objects. Therefore, the above Tom.ability.run='50 meters/10 seconds' changes the ability of the prototype connection, which affects another object Merry. In this case, you may ask Tom.ability = {......} Didn't it also change the ability on the prototype chain? Why was Merry not affected? The answer is that Tom.ability = {...} did not change the ability attribute on the prototype chain, but added a self-owned attribute ability for Tom. When accessing Tom.ability, you no longer need to access the ability on the prototype chain, but access its own attribute ability. This is the principle of proximity; OK, if you still have questions, you can use paper and pen to write down your questions and continue. You will understand better after watching.
2. The deep principle of JS prototype chain:
First, we must introduce a noun __proto__
, what is __proto__
? In my understanding, __proto__
is the real prototype chain, and prototype
is just a shell. If you are using the chrome browser, then you can try to use console.log(Tom.__proto__
.ability.run). You find that this way of writing is completely feasible, and in fact, when ability exists only on the prototype chain Attributes, Tom.ability actually points to Tom.__proto__
.ability; of course, if you try it in IE browser, you will definitely get an error. In fact, IE browser prohibits access to __proto__
access, while chrome allows it. Of course, in actual development, I do not recommend using the __proto__
attribute directly, but it often plays an important role when we debug the code. Some people may ask what the relationship is between Tom.__proto__
and Humans.prototype
. In order to clarify the relationship between the two, three rules are listed below:
1 , the object has the __proto__
attribute, but does not have the prototype
; for example: there is Tom.__proto__
, but there is no Tom.prototype
.
2. The class does not have the __proto__
attribute, but has prototype
; for example: there is no Humans.__proto__
, but there is Humans.prototype
(This must be corrected, and I am very grateful to 'Brother Chuanchuan' for pointing out this error. It is true that I did not think clearly when I wrote this point. In fact, Humans is also an instance object of Function, so Humans. __proto__
===Function.prototype
is absolutely true. What is a little special is that Function.prototype points to an Empty (empty) function at this time, which is worthy of consideration).
3、由同一个类实例化(new)得到的对象的__proto__
是引用该类的prototype
的(也就是我们说的引用传递);例如Tom和Merry的__proto__
都引用自Humans的prototype
。
OK,上面说过Tom.ability={……}其实并没有改变原型链上的ability属性,或者说并没有改变Tom.__proto__
.ability,而是为Tom添加了一个自有的ability属性,为了说明这一点,我们再次回到以上的第三个代码块,其代码如下:
function Humans() { this.foot = 2; } Humans.prototype.ability = { run : '100米/10秒', jump : '3米'};var Tom = new Humans();var Merry = new Humans(); Tom.ability = { run : '50米/10秒', jump : '2米'};console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'100米/10秒'console.log(Merry.ability.jump); //结果:'3米'
当为Tom.ability赋予新的值后,再次访问Tom.ability时就不再指向Tom.__proto__
.ability了,因为这时其实是为Tom添加了自有属性ability,可以就近取值了,你可以尝试用Chrome浏览器分别console.log(Tom.ability.run)和console.log(Tom.__proto__
.ability.run),你会发现确实存在两个不同的值,再看完下面的图后,相信你会完全明白: 于是可以有这样一个结论:当访问一个对象的属性或方法的时候,如果对象本身有这样一个属性或方法就会取其自身的属性或方法,否则会尝试到原型链(
__proto__
)上寻找同名的属性或方法。明白了这一点后,要解释以上第四个代码块的原理也非常容易了,其代码如下:
function Humans() { this.foot = 2; } Humans.prototype.ability = { run : '100米/10秒', jump : '3米'};var Tom = new Humans();var Merry = new Humans(); Tom.ability.run = '50米/10秒'; Tom.ability.jump = '2米';console.log(Tom.ability.run); //结果:'50米/10秒'console.log(Tom.ability.jump); //结果:'2米'console.log(Merry.ability.run); //结果:'50米/10秒'console.log(Merry.ability.jump); //结果:'2米'
当Tom.ability.run=’50米/10秒’的时候,JS引擎会认为Tom.ability是存在的,因为有Tom.ability才会有Tom.ability.run,所以引擎开始寻找ability属性,首先是会从Tom的自有属性里寻找,在自有属性里并没有找到,于是到原型链里找,结果找到了,于是Tom.ability就指向了Tom.__proto__
.ability了,修改Tom.ability.run的时候实际上就是修改了原型链上的ability了,因而影响到了所有由Humans实例化得到的对象,如下图:
希望上面所讲的内容足够清楚明白,下面通过类的继承对原型链作更进一步的深入:
先来看一个类的继承的例子,代码如下:
function Person() { this.hand = 2; this.foot = 2; } Person.prototype.say = function () { console.log('hello'); }function Man() { Person.apply(this, arguments);//对象冒充 this.head = 1; } Man.prototype = new Person();//原型链Man.prototype.run = function () { console.log('I am running'); }; Man.prototype.say = function () { console.log('good byte'); }var man1 = new Man();
以上代码是使用对象冒充和原型链相结合的混合方法实现类的继承,也是目前JS主流的实现类的继承的方法,如果对这种继承方法缺乏了解,可以看看这里。
接下来看看以上实现继承后的原型链,可以运用prototype
和__proto__
来解释其中的原理:
1、从man1 = new Man(),可以知道man1的__proto__
是指向Man.prototype的,于是有:
公式一:man1.__proto__
=== Man.prototype 为true
2、从上面的代码原型链继承里面看到这一句代码 Man.prototype = new Person(),作一个转换,变成:Man.prototype = a,a = new Perosn();一个等式变成了两个等式,于是由a = new Perosn()可以推导出a.__proto__
= Person.prototype,结合Man.prototype = a,于是可以得到:
公式二:Man.prototype.__proto__
=== Person.prototype 为true
由公式一和公式二我们就得出了以下结论:
公式三:man1.__proto__
.__proto__
=== Person.prototype 为true
公式三就是上述代码的原型链,有兴趣的话,可以尝试去推导多重继承的原型链,继承得越多,你会得到一个越长的原型链,而这就是原型链的深层原理;从公式三可以得出一个结论:当你访问一个对象的属性或方法时,会首先在自有属性寻找(man1),如果没有则到原型链找,如果在链上的第一环(第一个__proto__
)没找到,则到下一环找(下一个__proto__
),直到找到为止,如果到了原型链的尽头仍没找到则返回undefined(这里必须补充一点:同时非常感谢深蓝色梦想提出的疑问:尽头不是到了Object吗?是的,原型链的尽头就是Object,如果想问为什么,不妨做一个小小的实验:如果指定Object.prototype.saySorry = ‘I am sorry’,那么你会惊喜地发现console.log(man1.saySorry)是会弹出结果‘I am sorry’的)。
以上就是原型链的深层原理,说难其实也算容易,如果细心研究,会发现原型链上有很多惊喜。
相关文章:
相关视频:
JavaScript basic syntax and basic statement video tutorial
The above is the detailed content of Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
