Home Web Front-end JS Tutorial Detailed explanation of JavaScript inheritance system

Detailed explanation of JavaScript inheritance system

Jan 04, 2018 am 10:12 AM
javascript js Detailed explanation

I recently worked on a web project and came into contact with jquery and other frameworks. Although it is easy to use, I still want to learn Javascript. Today I will share my recent understanding of js prototype inheritance. I welcome corrections for any shortcomings. This article mainly introduces relevant information about the JavaScript inheritance system. Friends who need it can refer to it. I hope it can help everyone.

1. Prototype attributes and prototype objects of constructors

When I first come into contact with js, I usually follow the same example and use the function new to create an instance. I don’t know the reason. I only heard about functions in js. That is the object. It turns out that js does not use the class inheritance system in languages ​​​​such as Java, but uses prototype objects (prototypes) to implement the inheritance system. Specifically, "constructors" are used to implement class functions.

First explain the two important concepts in prototypal inheritance: prototype attributes and prototype objects (instances).

As far as the js object system is concerned, each function (constructor) created has a prototype prototype attribute. At the same time, each object instance created through the constructor also contains a _proto_ attribute, prototype and The _proto_ attribute is a pointer to the prototype object. The only difference between an ordinary function and a constructor is whether its prototype attribute prototype is a meaningful value.

The prototype pointed to by the prototype attribute prototype is an object instance. Specifically, as shown in the figure below, if the constructor Animal() has a prototype object B, all instances created by the constructor must be copied to B. That is: the _proto_ attribute of instance a1 of Animal() will also point to prototype object B. Therefore, instance a1 can inherit all properties, methods and other properties of B.

Figure 1 JS object instantiation implementation

2. Empty object

In JavaScript, "empty object" is the entire The foundation of the prototypal inheritance system is the foundation of all objects. Before introducing "empty objects", we must first introduce "empty objects (null)".

Empty object null

Null is not an "empty object". As a reserved word in JavaScript, its meaning is:

(1) It belongs to the object type

 (2) The object is a null value

As an object type, you can use for...in to enumerate it, but as a null value, null does not have any methods and attributes (including constructor, _proto_ and other attributes ), so nothing can be listed. As shown in the following example:  

var num=0;
  for(var propertyName in null)
  {
  num++;
  }
Copy after login

 Alert(num);//The display value is 0

The most important point is that null has no prototype, it is not self-defined by the Object() constructor (or other Subclass) is instantiated, and the instanceof operation on it will return false.

 2. "Empty object"

"Empty object" refers to a standard object instance constructed through Object(). For example:

obj=new Object();或 obj={};
Copy after login

"Empty object" has all the characteristics of "object", so it can access predefined properties and methods such as toString() and valueof.

 3. The relationship between "empty object" and null

As shown in the path shown by the red line in Figure 2 below, when the -proto-property of the Object prototype object is obtained through "Object.prototype._proto_" When, you will get "null", because the null object does not have any attributes, that is to say, "Object {}"

The prototype object is the end of the prototype chain.

Figure 2 js class inheritance system

3. Implementation of Javascript inheritance and prototype chain maintenance

(1) Implementation of inheritance

The first section said that class inheritance in JavaScript is achieved by modifying the prototype attribute prototype of the constructor. As shown in the following code:

function Animal() {
this.name = 'Animal';
};
function Dog() {
};
  Dog.prototype = new Animal();
var d = new Dog();
console.log(d.name);//'Animal'
Copy after login

By creating an instance of the Animal type and assigning it to the prototype attribute of the constructor Dog(), type inheritance is achieved, that is, Animal is the parent class of Dog. In this way, instance d of Dog type can also access the name attribute of Animal type.

(2) Prototype chain

There are two prototype chains in the JS object inheritance system: "internal prototype chain" and "constructor prototype chain". As shown in Figure 3, the black arrow indicates that the path is the "constructor prototype chain" maintained through the prototype attribute of the constructor. The red arrow indicates that the path is the "internal prototype chain" maintained through the _proto_ attribute of the object instance.

Figure 3 Prototype chain

(3) Prototype chain maintenance

Figure 3 illustrates that the constructor builds a prototype through the displayed prototype chain, and object instances also build a prototype chain through the _ proto _ attribute. Since _ proto _ is an inaccessible internal property (the value of the object _ proto _ property can be viewed in Chrome, but cannot be modified), the entire prototype chain cannot be accessed starting from the instance dog1 of the subclass (Dog). Therefore, we need to find a connection point from the "internal prototype chain" and "constructor prototype chain" in Figure 3, so that when the instance cannot access obj._proto_, the internal prototype chain is accessed through the constructor (the two prototypes are chain in series).

To access the entire prototype chain starting from an instance of a subclass, you need to use the constructor attribute of the instance to maintain the prototype chain.

其实,JavaScript已经为构造器维护了原型属性,根据如下测试代码,当我们自定义一个构造器时,其原型对象是一个Object()类型的实例,但是其原型对象的constructor属性默认总是指向构造器自身,而非指向其父类Object。如图4中构造器实例中蓝色框中的constructor属性,该constructor属性继承自原型对象,因此可以得出一个自定义的构造器产生的实例,其constructor属性默认总是指向该构造器。

function Animal() {
};
var a = new Animal();
console.log(Animal.prototype);//Object(){}
console.log(Animal.prototype.constructor === Animal);//true//true
Copy after login

  

图4

  因此,在_proto_属性不可访问时,可通过a1.constructor.prototype获取实例a1的原型对象。然而,当我们自定义一个构造函数Dog(),并且手动指定其prototype属性值为Animal,即指定Dog的父类为Animal。此时访问d1.constructor值为Animal,而不是Dog;由图5可以看出,Dog的原型对象和dog分别由Animal()和Dog()两个不同的构造器产生,然而他们的constructor属性指向了相同的构造器(Animal),这样就与使用constructor属性串联两种原型链的设想冲突了。

图5

  是构造器出问题还是原型出了问题?图5可以看出,原型继承要求的“复制行为”已经正确实现,能够从子类实例中访问原型对象属性,问题是在给子类构造器Dog()赋予一个原型对象时应该“修正”该原型对象的构造属性值(constructor)。ECMAScript 3标准提供的方法是:保持原型的构造器属性,在子类构造器中初始化其实例对象的构造属性。代码如下: 

function Dog () {
  //初始化constructor属性
   this.constructor=Dog; //或 this.constructor=arguments.callee;
  };
  Dog.prototype = new Animal();//赋予原型对象,实现继承
Copy after login

图6

对constructor属性“修正”后效果如图6所示,在子类构造器Dog中初始化其实例对象的constructor属性后,Dog的实例对象的constructor都指向Dog,而Dog的原型对象的constructor仍然指向父类型构造器Animal。这样就可以实现利用constructor属性串联起原型链,可以从子类实例开始回溯整个原型链。

相关推荐:

详解php中的类与对象(继承)_php实例

JS原型继承四步曲

JavaScript中关于继承的六种实现方式

The above is the detailed content of Detailed explanation of JavaScript inheritance system. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

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

See all articles