Table of Contents
_proto_and prototype
Home Web Front-end JS Tutorial Detailed explanation of prototype chain in JS

Detailed explanation of prototype chain in JS

Mar 22, 2018 pm 05:19 PM
javascript prototype Detailed 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...
   //执行构造函数,并返回创建的对象。
Copy after login

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;完美结束原型链。
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login
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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles