search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript inheritance system

Detailed explanation of JavaScript inheritance system

Jan 04, 2018 am 10:12 AM
javascriptjsDetailed 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++;
  }

 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={};

"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'

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

  

图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();//赋予原型对象,实现继承

图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
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: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools