search
HomeWeb Front-endJS TutorialA detailed explanation of the inheritance mechanism in js

Preface

I have been learning vue recently, and I finally have time to write something on the weekend (I am a little excited when I think about being able to deceive likes again!). In the basics of JavaScript, in addition to closures, inheritance is also a difficulty. Because of the length of the article, I plan to divide it into two parts. Also based on "Javascript Advanced Programming", I will give a detailed explanation. If there is anything wrong, please correct me.

Preparatory knowledge

In order to better explain inheritance, let’s put some preparatory knowledge first.

1. Constructor, instance

Constructor is a function used to create objects, and is essentially a function. The difference from other functions is that the calling method is different:

  • If it is called through the new operator, it is the constructor

  • If it is not called through the new operator, it is an ordinary function
    Example:

function Person(name, age) {
   this.name = name;
   this.age = age;
 }
 //当做构造函数调用
 var person1 = new Person('Mike',10);
 
 //当做普通函数调用,这里相当于给window对象添加了name和age属性,这个不是重点,只要注意调用方式
 Person('Bob',12);
 
 console.log(person1)//Person {name: "Mike", age: 10}
 console.log(name)//Bob
 console.log(age)//12

in var person1 = new Person('Mike',10);, the function Person is called through the new operator, and person1 is generated. The Person here is Called the
constructor , person1 is called a instance of the Person function object. There will be a constructor attribute in the instance, pointing to the corresponding constructor , see the following example:

 function Person(name, age) {
    this.name = name;
    this.age = age;
  }
 var person1 = new Person('Mike',10);
 var person2 = new Person('Alice',20);
 console.log(person1.constructor)//function Person(){省略内容...}
 console.log(person2.constructor)//function Person(){省略内容...}

2. Prototype object

When we Every time a function is created, the function object will have a

prototype attribute, which is a pointer that points to its prototype object. The essence of the prototype object is also an object. This sentence may be a bit difficult to understand when you first read it. For example, take the function just now:

function Person(name, age) {
        this.name = name;
        this.age = age;
     }
     console.log(Person.prototype)//object{constructor:Person}

You can see that

Person.prototype points to an object, which is the prototype of Person Object , and this object has a constructor attribute, which points to the Person function object. Feeling a little dizzy? It doesn't matter, next we will use a better method than giving examples-drawing pictures.

3. The relationship between constructor, prototype object and instance

In front, we have just introduced the constructor, instance and prototype object. Next, we use a picture to represent these three (It’s really troublesome to draw this kind of picture with PS. If you have any good tools to recommend):


A detailed explanation of the inheritance mechanism in js From the picture we can see:

  • The

    prototype of the function object points to the prototype object, and the constructor of the prototype object points to the of the instance object

  • of the function object The [Protoptype] attribute points to the prototype object . The [Protoptype] here is the internal property . It can be understood that it exists, but it is not allowed. When we access (although some browsers allow access to this attribute, let's understand it this way first), the function of this attribute is: Allow the instance to access the properties and methods in the prototype object through this attribute. For example:

  • function Person(name, age) {
            this.name = name;
            this.age = age;
          }
          //在原型对象中添加属性或者方法
         Person.prototype.sex = '男'; 
         var person1 = new Person('Mike',10);
         var person2 = new Person('Alice',20);
         //只给person2设置性别
         person2.sex = '女';
         console.log(person1.sex)//'男'
         console.log(person2.sex)//'女'
Here we do not set the

sex attribute for the person1 instance, but because of [Protoptype] exists, the corresponding attribute in the prototype object will be accessed; At the same time, after we set the
sex attribute to person2, the output is 'female', indicating that only when the instance itself does not have the corresponding attribute or method Only then will we find the corresponding properties or methods on the prototype object

Inheritance

Prototype chain

In js, the main idea of ​​inheritance is to use the prototype chain , so if you understand the prototype chain, the inheritance problem is half understood. You can take a short break here. If you have almost understood the previous preparatory knowledge, you can start talking about the prototype chain.

The principle of the prototype chain is to let one reference type inherit the properties and methods of another reference type. Let’s review the knowledge just mentioned:

  • Prototype object points to the constructor through the constructor attribute

  • InstancePoints to the prototype object through the [Prototype] attribute

Now let’s think about a question:

What happens if the prototype object is equal to an instance of another constructor? For example:

    function A() {
     
    }
    //在A的原型上绑定sayA()方法
    A.prototype.sayA = function(){
            console.log("from A")
    }
    function B(){

    }
    
     //让B的原型对象指向A的一个实例
     B.prototype = new A();
     
     //在B的原型上绑定sayB()方法
     B.prototype.sayB = function(){
            console.log("from B")
     }
     //生成一个B的实例
     var a1 = new A();
     var b1 = new B();
     
     //b1可以调用sayB和sayA
     b1.sayB();//'from B'
     b1.sayA();//'from A'

In order to easily understand what just happened, let’s take another picture:


A detailed explanation of the inheritance mechanism in jsNow look at the code combined with the picture:

  • First, we created two function objects A and B,

    and also generated their prototype objects

  • Next, we added the sayA() method
    * to the prototype object of A, and then the critical step B.prototype = new A() ;, we let the protytype pointer of function object B point to an instance of A, please pay attention to my description: let the of function object B The protytype pointer points to an instance of A, which is why in the end, B's prototype object no longer has a constructor attribute. In fact, B originally had a real prototype object, which could have been passed B.prototype access, but we have now rewritten this pointer so that it points to another object, so the real prototype object of B cannot be accessed now. Instead, the new prototype object is an instance of A, so naturally there is no constructorAttribute

  • Next we add a sayB method# to the object pointed to by B.prototype

  • ##Then, we generated an instance b1

  • Finally, we called the sayB method of b1, which can be executed. Why?


    Because b1 has a [Prototype] property that can access the methods in B prototype;

  • We called the sayA method of b1, Can be executed, why?


    Because b1 can access B prototype along the [Prototype] property, B prototype continues to access A prototype along the [Prototype] property, and finally on A.prototype The sayA() method is found, so it can be executed

So, the current result is equivalent to,

b1 inherits the properties and methods of A, this A structure that [Prototype] continuously connects instances and prototype objects is the prototype chain. It is also the main implementation method of inheritance in js. Original text from https://segmentfault.com/a/1190000007376061

The above is the detailed content of A detailed explanation of the inheritance mechanism 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
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools