Table of Contents
Preface
Preparatory knowledge
1. Constructor, instance
Home Web Front-end JS Tutorial A detailed explanation of the inheritance mechanism in js

A detailed explanation of the inheritance mechanism in js

Oct 24, 2017 am 09:16 AM
javascript inherit

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

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(){省略内容...}
Copy after login

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

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)//'女'
    Copy after login
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'
Copy after login
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 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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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 C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

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

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? Detailed explanation of C++ function inheritance: How to understand the 'is-a' and 'has-a' relationship in inheritance? May 02, 2024 am 08:18 AM

Detailed explanation of C++ function inheritance: Master the relationship between "is-a" and "has-a" What is function inheritance? Function inheritance is a technique in C++ that associates methods defined in a derived class with methods defined in a base class. It allows derived classes to access and override methods of the base class, thereby extending the functionality of the base class. "is-a" and "has-a" relationships In function inheritance, the "is-a" relationship means that the derived class is a subtype of the base class, that is, the derived class "inherits" the characteristics and behavior of the base class. The "has-a" relationship means that the derived class contains a reference or pointer to the base class object, that is, the derived class "owns" the base class object. SyntaxThe following is the syntax for how to implement function inheritance: classDerivedClass:pu

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' 'Introduction to Object-Oriented Programming in PHP: From Concept to Practice' Feb 25, 2024 pm 09:04 PM

What is object-oriented programming? Object-oriented programming (OOP) is a programming paradigm that abstracts real-world entities into classes and uses objects to represent these entities. Classes define the properties and behavior of objects, and objects instantiate classes. The main advantage of OOP is that it makes code easier to understand, maintain and reuse. Basic Concepts of OOP The main concepts of OOP include classes, objects, properties and methods. A class is the blueprint of an object, which defines its properties and behavior. An object is an instance of a class and has all the properties and behaviors of the class. Properties are characteristics of an object that can store data. Methods are functions of an object that can operate on the object's data. Advantages of OOP The main advantages of OOP include: Reusability: OOP can make the code more

C++ function inheritance explained: When should inheritance not be used? C++ function inheritance explained: When should inheritance not be used? May 04, 2024 pm 12:18 PM

C++ function inheritance should not be used in the following situations: When a derived class requires a different implementation, a new function with a different implementation should be created. When a derived class does not require a function, it should be declared as an empty class or use private, unimplemented base class member functions to disable function inheritance. When functions do not require inheritance, other mechanisms (such as templates) should be used to achieve code reuse.

See all articles