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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

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.

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 Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools