search
HomeWeb Front-endJS TutorialHow to implement parasitic composable inheritance using JavaScript

This article mainly introduces JavaScript parasitic combined inheritance, and analyzes the principles, implementation methods and related precautions of parasitic combined inheritance in detail in the form of examples. Friends in need can refer to the following

The examples in this article describe JavaScript parasitic composable inheritance. I share it with you for your reference. The details are as follows:

In fact, the book "JavaScript Advanced Programming" already has the complete code. As long as you understand the code, you will know what this inheritance is about.

First of all, in js, there are two ways to define attributes for objects:

//通过执行构造函数设置属性
function A(){
  this.a = 1;
}
//通过原型设置属性
A.prototype.b = 1;

So:

If a class Sub wants to inherit another class Super, it needs to inherit the parent class Attributes under the prototype, you also need to execute the constructor of the parent class.

That is, If a class Sub wants to inherit another class Super, it must not only realize the inheritance of prototype properties and methods through the prototype chain, but also realize the inheritance by calling the parent class constructor in the subclass constructor. Inheritance of instance properties.

1. Inherit the attributes under the prototype

As you can see above, the attributes under the prototype of the Super class are not inherited, so this part needs to be inherited below. .

Direct "=" will definitely not work, because after modifying the properties in Sub.prototype, it cannot affect the objects in Super.prototype, that is, it cannot Sub.prototype=Super.prototype.

First write a method to create a copy of the object

function object(o){
  function A(){}
  A.prototype = o
  var ox = new A()
  return ox
}

The object ox obtained by the above function has all the properties of the object o (on the prototype chain), and modifying the properties of ox does not It will affect o, which is equivalent to making a copy of o.

Prototypal inheritance is the "object" function above, which can be found in many class library source codes

Simply speaking, prototypal inheritance means that there is no need to instantiate the parent class. Directly instantiating a temporary copy implements the same prototype chain inheritance. (That is, the prototype of the subclass points to the instance of the copy of the parent class to achieve prototype sharing)

tips: As we all know, prototype chain inheritance is achieved by pointing the prototype of the subclass to the instance of the parent class. Prototype sharing, and prototypal inheritance is that the prototype of the subclass points to an instance of the copy of the parent class to achieve prototype sharing.

ECMAScirpt 5 standardizes prototypal inheritance through the new Object.create() method.

Using the object method, you can "copy" the properties of Super.prototype to Sub.prototype. Of course, you also need to correct the pointing of the constructor here.

function inherit(subType,superType){
 var prototype=Object.create(superType.prototype);
 prototype.constructor=subType;
 subType.prototype=prototype;
}

2. Execute the constructors of the parent class and the subclass respectively, and inherit the attributes under this part:

//父类
function Super(){
this.sss=1
}
//子类
function Sub(){
//arguments是Sub收到的参数,将这个参数传给Super
Super.apply(this, arguments)
}
//实例
sub = new Sub()

Super.apply(this, arguments )This sentence executes the Super class as an ordinary function, but the this of the Super class is replaced by this of the Sub class, and the parameters received by Sub are also passed to Super

The final execution result Equivalent to sub.sss=1

Attached are the characteristics, advantages and disadvantages of various inheritance methods

There was a time when JavaScript was not standardized regarding class implementation inheritance, resulting in There are various codes that implement inheritance; in fact, no matter how the code changes, inheritance is based on two methods:

1. Through the prototype chain, that is, the prototype of the subclass points to the parent class instances to achieve prototype sharing.
2. Borrow the constructor, that is, through js's apply and call, the subclass can call the attributes and methods of the parent class;

The prototype chain method can realize all attribute methods Sharing, but properties and methods cannot be exclusive (for example, Sub1 modifies the function of the parent class, and all other subclasses Sub2, Sub3... cannot call the old function);

And Borrowing constructors In addition to exclusive properties and methods, parameters can also be passed in subclass constructors, but the code cannot be reused. Generally speaking, can realize the exclusive use of all attribute methods, but cannot achieve the sharing of attributes and methods. (For example, if Sub1 adds a new function, and then wants to use it in Sub2, Sub3... It is impossible to implement, only Sub2, Sub3... can be added in the constructor respectively).

Combined inheritance is to use the above two inheritance methods together. Shared properties and methods are implemented using prototype chain inheritance, and exclusive properties and methods are implemented using borrowed constructors. Therefore, combined inheritance almost perfectly implements js inheritance; why is it said "almost"? Because geeks who are serious about it discovered that there is a small bug in combinatorial inheritance. When implementing it, the super class (parent class) was called twice. Is it possible that the performance is not up to standard? How to solve it? So "parasitic inheritance" came out.

Parasitic inheritance (prototypal inheritance) means that there is no need to instantiate the parent class. Instead, a temporary copy is directly instantiated to achieve the same prototype chain inheritance. (That is, the prototype of the subclass points to the instance of the copy of the parent class to achieve prototype sharing)

"Parasite combination inheritance" uses "parasitic inheritance" to fix the small bug of "combination inheritance", thus making js Perfect implementation is inherited.

Example code:

function SuperType(name,colors){
  this.name=name;
  this.colors=colors;
}
SuperType.prototype.getSuperProperty=function(){ return this.name; }
function SubType(job,name,colors){
  SuperType.call(this,name,colors);
  this.job=job;
}
SubType.prototype.getSubPrototype=function(){ return this.job; }
function inherit(subType,superType){
  var prototype=Object.create(superType.prototype);
  prototype.constructor=subType;
  subType.prototype=prototype;
}
inherit(SubType,SuperType);
var instance=new SubType("doctor","John",["red","green"]);
console.log(instance.getSubPrototype());  //输出"doctor"
console.log(instance.getSuperProperty());  //输出"John",成功调用在父类原型定义的方法

The attribute inheritance code isSuperType.call(this,name,colors);

The prototype inheritance code is inherit(SubType,SuperType);

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

related articles:

How to implement collision detection in JS

How to use it with gulp and bower in angular1?

What are the methods for debugging js scripts?

How to implement a search box using Angular

Detailed introduction to interpolation in vue

The above is the detailed content of How to implement parasitic composable inheritance using JavaScript. 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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.