search
HomeWeb Front-endJS TutorialUnderstanding 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),你会发现确实存在两个不同的值,再看完下面的图后,相信你会完全明白:
Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain于是可以有这样一个结论:当访问一个对象的属性或方法的时候,如果对象本身有这样一个属性或方法就会取其自身的属性或方法,否则会尝试到原型链(__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实例化得到的对象,如下图:
Understanding of objects that cannot be used in the prototype chain and in-depth discussion of the JS prototype chain

希望上面所讲的内容足够清楚明白,下面通过类的继承对原型链作更进一步的深入:
先来看一个类的继承的例子,代码如下:

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’的)。

  以上就是原型链的深层原理,说难其实也算容易,如果细心研究,会发现原型链上有很多惊喜。

相关文章:

js中的作用域链和原型链以及原型继承

js的原型及原型链详解

相关视频:

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.