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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

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.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor