search
HomeWeb Front-endJS TutorialDetailed explanation of prototype chain in JS

Detailed explanation of prototype chain in JS

Mar 22, 2018 pm 05:19 PM
javascriptprototypeDetailed explanation


Although JS is not an object-oriented language, this does not mean that JS cannot implement OOP features. I believe that when you use JS, you must have used the prototype methods of Object, such as call, apply, hasOwnProperty, etc., but where do these methods come from? If JS cannot implement inheritance, the use of these methods will be impossible. Here we will talk about the method of implementing inheritance in JS, the prototype chain.

_proto_and prototype

First we need to understand what a normal object is and what a function object is.

  • Common object

    • var a = {}

    • var a = new Object();

    • var a = new f1();//The same way as the previous object was created

  • ##Function object


    • var a = function(){};

    • var a = new Function() {};

    • f1()

_proto_ is an attribute owned by every ordinary object and is used to point to the constructor The prototype is the prototype object of the constructor. The prototype object of the constructor is generally an ordinary object (

When the constructor is Function, it becomes a function object), so it also has the _proto_ attribute. And its _proto_ points to the prototype object of its constructor, which is Object.prototype. The last Object.prototype._proto_ points to null, reaching the top of the prototype chain. Prototype is an attribute owned by function objects. It is assigned to a new object instance when the object is created. Of course, it can also be modified dynamically.

   function Person(){};   var p = new Person();//创建一个普通对象
   //创建过程实际为
   var p={};
   p._proto_=Person.prototype;
   Person.apply(p,arguments);//或者是call...
   //执行构造函数,并返回创建的对象。

Supplementary explanation of the above code

Normally speaking, there is no need to write a return statement in the constructor, because it will return the newly created object by default. However, if a return statement is written in the constructor, if the return is an object, then the function will overwrite the newly created object and return this object; if the return is a basic type such as string, number, Boolean value, etc. , then the function will ignore the return statement or return the newly created object.

The default value of the prototype object of the constructor is:

  Person.prototype={
    constructor://指向构造函数本身
    _proto_://指向构造函数Person的原型对象的构造函数的原型对象,这里是指Object.prototype
  }
  //这里有一个特殊情况——当构造函数为Function的时候
  Function.prototype._proto_===Object.prototype 
  //我们知道Function.prototype是一个函数对象,它的_proto_应该指向它的构造函数的原型,也就是Function.prototype。
  //可是这样下去就没完没了了,毕竟一条链总是有顶端的。这里约定Function.prototype._proto_===Object.prototype;  //这时,Object.prototype._proto_===null;完美结束原型链。

We can continuously modify the pointing of the prototype object of the constructor, so that a chain can eventually be formed. The chain mentioned above is the default prototype chain in JS.

Talk about code implementation

Let’s take a look at the code:

  function Parent(name){
        this.name=name||"parent";
    }    function Son(name){
        this.name=name||"son";        this.property="initial Son name";
    }    function Grandson(name){
        this.name=name||"grandson";        this.ggs="initial Grandson name";
    }

    Son.prototype = new Parent("原型中的Parent");
    Grandson.prototype = new Son("原型中的Son");    let grandson = new Grandson("孙子");
    console.log(grandson instanceof Son);//true
    console.log(grandson instanceof Grandson);//true
    console.log(grandson instanceof Parent);//true

Detailed explanation of prototype chain in JSObviously, true is output in the end. But let’s change the code a little:

    Grandson.prototype = new Son("原型中的Son");
    Son.prototype = new Parent("原型中的Parent");//其实上一步已经实例化了一个Son的对象给Grandson.prototype
    //这个时候Son的实例的_proto_已经确定指向那个时候的构造函数.prototype了(默认原型对象)
    let grandson = new Grandson("孙子");
    console.log(grandson instanceof Son);//false
    console.log(grandson instanceof Grandson);//true
    console.log(grandson instanceof Parent);//false

Detailed explanation of prototype chain in JSWhy does the result change? The reason is also very simple. We mentioned before the creation process of object creation: when the object is instantiated, the prototype of the constructor has been assigned to the object's _proto_. That is to say, the value of Grandson.prototype._proto_ has been determined in the first line of the above code. Even if Son.prototype is modified in the second line, the value of Grandson.prototype._proto_ cannot be modified.

Conclusion: The relationship of the prototype chain in JS is maintained by _proto_, not prototype.

Quick test

var animal = function(){}; var dog = function(){};

 animal.price = 2000;
 dog.prototype = animal; var tidy = new dog();
 console.log(dog.price) 
 console.log(tidy.price)

What is the answer to the output? It's undefined and 2000, let's analyze it:

First of all, we know that animal and dog are both function objects. In the fourth line, the prototype object of dog is modified to animal. Then let's look down,
console.log(dog.price) This sentence will first look for the price of dog, and there is none. Then go look for it on the prototype chain. How did you find it? We mentioned before that we use _proto_ to get to the prototype object of its constructor. Since dog is a function object, the prototype object of its constructor is Function.prototype, which is an empty function. So undefined is returned, and the price attribute is not found. What about
console.log(tidy.price)? tidy is an ordinary object. First of all, we are looking for its own attribute price, but there is none. Go to the prototype object of its constructor through _proto_, which is dog.prototype. Because tidy is instantiated after
dog.prototype = animal;, the point of tidy._proto_ already points to the modified dog.prototype. That is to say, it points to animal, that is, the price attribute can be found, so 2000 is output.

All properties and methods on the prototype object can be regarded as public (protected) properties and methods of the parent class in Java. You can use this inside these methods to access the properties and methods in the constructor. method. As for why, this has to mention the binding issue of this in JS... In short, whoever calls the function, this will point to. Except arrow functions...

Related recommendations:

Detailed explanation of JS prototype and prototype chain (1)

Detailed explanation of JS prototype and prototype chain (2)

Detailed explanation of JS prototype and prototype chain (3)

The above is the detailed content of Detailed explanation of prototype chain in JS. 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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.